MATLAB Answers

How to add values to structure array without loop

189 views (last 30 days)
Consider the following loop:
values = [2 5 6 4 8 9 10 5 15 7]
for i=1:10
arr(i).myfield = values(i);
end
How can this be done without loop?
Thank you.

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Dec 2015
T = struct('myfield', num2cell(values));
arr(1:length(T)) = T;
In the special case that arr does not already exist, it can be done with the one line
arr = struct('myfield', num2cell(values));

  4 Comments

Show 1 older comment
Walter Roberson
Walter Roberson on 8 Dec 2015
T = num2cell(values);
[arr(1:10).myfield2] = T{:};
It is necessary to use two lines for this.

Sign in to comment.

More Answers (0)