MATLAB矢量化:从矢量元素填充结构域

时间:2015-02-22 23:24:51

标签: matlab vector struct vectorization

我有一个结构矢量,每个结构都有一个字段x

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

我想从给定的向量x中设置S中所有结构的字段X,即我想对以下循环进行向量化:

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

这可能吗?

2 个答案:

答案 0 :(得分:4)

你可以这样做:

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

对于7.0之前的Matlab版本,第二行should be changed进入

[S.x] = deal(Xc{:}); %// generate comma-separated list from cell array, and assign

答案 1 :(得分:0)

如果您事先知道这些值,可以像这样初始化:

S = struct('x', {1 2 3})
相关问题