# adding a struct to struct array

조회 수: 85(최근 30일)
Robert Alvarez 2013년 4월 1일
I like to return mutltiple outputs from a function as a struct. Many times I call the function in a loop and I want to gather the results for all iterations as a struct array. Then I can, for example, access all individual fields using a bracket.
My question is how to add the return-structs to the struct array so each member of the array has the return-struct fields.
This does not work:
>> sarry = struct([]);
>> sarry(end+1) = myfunc(foo);
??? Subscripted assignment between dissimilar structures.
I wrote a function that does what I want--see below.
Is there an easier way to do it?
Bob
p.s. here is my function:
fnames = fieldnames(s);
sarray(end+1).(fnames{1}) = s.(fnames{1});
if length(fnames) > 1
for k = 2:length(fnames)
sarray(end).(fnames{k}) = s.(fnames{k});
end
end
p.p.s. I ran across this idea but it assumes that the inputs to the function in different iterations of the loop are the integers. It could be extended but does not allow other code within the loop.
T = arrayfun(@(K) CreateAsStruct(K), 1:n, 'UniformOutput',0);
array = horzcat(T{:});
clear T

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

### 채택된 답변

Darik 2013년 4월 1일
편집: Darik 2013년 4월 1일
You can skip the first assignment of the empty struct, a la
clear sarray; sarray(1) = myfunc(foo);
So you could just run the for loop backwards to combine the array preallocation and the function calls: clear sarray; for i = n:-1:1 sarray(i) = myfunc(foo(i)); end
Those 'clear sarray' lines aren't necessary, it's just to make clear that sarray hasn't been defined before the first indexed assignment
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Darik 2013년 4월 1일
And if you can't run the loop backwards, you can include an extra preallocation step like this:
clear sarray;
sarray(1:n) = myfunc(foo(1));
for i = 2:n
sarray(i) = myfunc(foo(i));
end

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

### 추가 답변(1개)

Robert Alvarez 2013년 4월 1일
Thanks, Darik. That is a good method.
However, it does not seem to work if the function returns structs with different fields depending, for example, on the parameters passed to it. Also, sometimes the parameters passed to the function depend on the order of executing the loop or there may be a variable, non-calculable, loop length.
In those cases I think the AddStruct2StructArray function will work so it is good to have both in my tool kit.
I am interested if there are other approaches. One possibility I have seen mentioned is to use a cell array but I have not been able to figure out how to convert it to a struct array easily.

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

### Community Treasure Hunt

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

Start Hunting!

Translated by