1

I would like to know the Matlab way of doing this:

I have an array of structs (Line) called lines.

Each Line looks like:

point1: [1 128]
point2: [218 128]
 theta: -90
   rho: -127

I need to subtract a value from all the point1(2) and point2(2) of all the lines in struct.

8
  • Can you develop more about your struct. It like Line.point1 = Array 2x1 ? Commented Sep 26, 2013 at 20:02
  • This is a great candidate for generating a lines class, with a method to subtract a scalar from that element of that field. Commented Sep 26, 2013 at 20:05
  • Yes Alexander, If I write that on the console I get ans = 1 128. They are the X and Y coords of the point Commented Sep 26, 2013 at 20:05
  • 1
    It's possible, see my solution. ;) Updated for point1(s). Commented Sep 26, 2013 at 20:24
  • 2
    Take into account that arrayfun may be slower than a for loop Commented Sep 26, 2013 at 20:40

2 Answers 2

2

The one-line solution for point1 would use arrayfun and setfield/getfield as follows,

lineStructArray2 = arrayfun(@(x) (setfield(x,'point1',getfield(x,'point1')+[0 dy])), lineStructArray)

where dy is the value you want to add (negative for subtract) from point1(2). Make a similar command for point2.

Sign up to request clarification or add additional context in comments.

Comments

0

If your array is made like this :

myArray = [line line2];

So you have a struct array. You can't acces it with

myArray(:).point1(2);

So you have to create a loop

myStoringArray = [];
for it = 1:size(myArray,2)
  myStoringArray = [myStoringArray myArray(it).point1(2)];
end

1 Comment

And beware, a struct array must contain all same struct. So all your line need point1, point2, theta and rho define or at least set null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.