prs
prs

Reputation: 23

how is the best way to create a struct in a loop?

I want to create a struct in a loop. this is the initial command lines:

for i = 1:n
     if condition
         myStruct(i).a = i:
         myStruct(i).b = 1:
     else
         myStruct(i) = myFunction(i):
     end
 end

myFunction is as follow: (real one has more fields)

function myStruct = myFunction(i)
myStruct.a = i;
myStruct.b = 0;
end

when the condition is true for the very first loop (i=1) it works fine, otherwise there is an error with the first assignment as follow:

subscripted assignment between dissimilar structures.

In order to Cope it I did as following but I'm looking for a better more efficient solution.

for i = 1:n
     if condition
         myStruct(i).a = i:
         myStruct(i).b = 1:
     else
         if i == 1
             myStruct = myFunction(i);
         else
             myStruct(i) = myFunction(i):
         end
     end
 end

but I prefer some shorter solution. I appreciate any suggestion.

Upvotes: 2

Views: 330

Answers (2)

Jeremy
Jeremy

Reputation: 85

Using arrayfun is more efficient for this. If myFunction always returns a struct with the same members, try:

myStruct = arrayfun(@myFunction, 1:n);

Edit for clarification:

When you add on every iteration you are changing the dimension of the array every iteration. This is not efficient. Arrayfun allows Matlab to preallocate the struct array and manage value assignment for you.

Edit to address edited OP

Updated function:

function myStruct = myFunction(i, condition)
myStruct.a = i;
if condition
    myStruct.b = 1;
else
    myStruct.b = 0;
end
end

Updated call:

s = arrayfun(@(x) myFunction(x, condition), 1:n);

Upvotes: 3

Ander Biguri
Ander Biguri

Reputation: 35525

As others have already commented here: Preallocate, and forget about the i==1 case.

myStruct(n) = myFunction(n); % or any other way of creating an instance of your structure, not important. 
for i = 1:n
     if condition
         myStruct(i).a = i:
         myStruct(i).b = 1:
     else
         myStruct(i) = myFunction(i):
     end
 end

Upvotes: 1

Related Questions