4

I have a vector of structs each having a field x:

s1.x = 1;
s2.x = 2;
s3.x = 3;
S = [s1, s2, s3];

I would like to set the field x of all structs in S from a given vector X, i.e. I would like to vectorize the following loop:

X = [97, 98, 99];
for i = 1 : length(S)
    S(i).x = X(i);
end

Is this possible?

0

2 Answers 2

4

You can do it this way:

Xc = num2cell(X); %// convert X to cell array of numbers
[S.x] = Xc{:}; %// generate comma-separated list from cell array, and assign

For Matlab versions before 7.0 the second line should be changed into

[S.x] = deal(Xc{:}); %// generate comma-separated list from cell array, and assign
Sign up to request clarification or add additional context in comments.

7 Comments

Great, that does it! Could you please explain why this works and [S.x] = X doesn't? Sometimes this vectorization stuff seems a little bit like voodoo to me.
You can omit the deal if we're dealing with cell arrays, so just do it like: [S.x] = Xc{:};
@MGA: X is a vector and Xc{:} is a comma-separated list. Simply converting to another data structure in between to get it done. @Luis Mendo: deal could be removed to get an even shorter solution.
@rayryeng I'm too old-style with deal I guess... Thanks!
@LuisMendo - lol no problem. Mind you for everything else, you would need the deal, but with cell arrays you can omit it. I figured it may save some clock cycles, but the deal is certainly more explicit!
|
0

If you know the values in advance, you can initialize like this:

S = struct('x', {1 2 3})

1 Comment

Good tip, but that's not what I'm after. S already exists, and I want to replace all the x fields at once from the vector X.

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.