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

1 view (last 30 days)
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

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
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))

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2007a

Community Treasure Hunt

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

Start Hunting!