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
2009-6-27
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!