MATLAB vectorization: filling struct fields from vector elements

你。 提交于 2019-12-22 08:39:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!