How to add values to structure array without loop

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.

 채택된 답변

Walter Roberson
Walter Roberson 2015년 12월 8일
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

Thanks Walter. But arr already exists with other fields. For example
arr(1).myfield1=10;
arr(2).myfield1=20;
arr(3).myfield1=30;
And I want to add another field myfield2 with values as below
values = [100 200 300];
for i=1:3
arr(i).myfield2 = values(i);
end
When I used your code
T = struct('myfield2', num2cell(values));
arr(1:length(T)) = T;
I got the following error message
Subscripted assignment between dissimilar structures.
T = num2cell(values);
[arr(1:10).myfield2] = T{:};
It is necessary to use two lines for this.
Thanks. It works now.
Great!!!!!!!!!!!! thank you

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by