How do I avoid a nested loop when assigning vales to a multidimensional structure in MATLAB 7.4 (R2007a)?

1 次查看(过去 30 天)
I have created a 2x4 structure and a 2x4 matrix like this:
s = repmat(struct('a', 0), 2, 4);
xx = [11 12 13 14;21 22 23 24];
Now I want to assign s(i,j).a = xx(i,j), and I would like to do it vectorized not with a nested loop like this:
for i = 1:2
for j = 1:4
s(i,j).a = xx(i,j);
end
end

采纳的回答

MathWorks Support Team
By using the functions MAT2CELL, CELL2STRUCT and RESHAPE you can avoid using a nested loop when assigning values to the multidimensional structure.
s1 = repmat(struct('a', 0), 2, 4);
xx = [11 12 13 14;21 22 23 24];
c=mat2cell(xx(:),ones(numel(xx),1),1)
s2=cell2struct(c,'a',2)
s3=reshape(s2,size(xx))

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2007a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by