MATLAB向量化:从向量元素填充结构字段 [英] MATLAB vectorization: filling struct fields from vector elements
本文介绍了MATLAB向量化:从向量元素填充结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个结构向量,每个结构都有一个字段x
:
I have a vector of structs each having a field x
:
s1.x = 1;
s2.x = 2;
s3.x = 3;
S = [s1, s2, s3];
我想根据给定的矢量X
设置S
中所有结构的字段x
,即我想对以下循环进行矢量化:
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
这可能吗?
推荐答案
您可以这样做:
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版本,应将第二行更改
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
这篇关于MATLAB向量化:从向量元素填充结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文