问题
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?
回答1:
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
回答2:
If you know the values in advance, you can initialize like this:
S = struct('x', {1 2 3})
来源:https://stackoverflow.com/questions/28664640/matlab-vectorization-filling-struct-fields-from-vector-elements