Reputation: 39
I have a loop which iterates for 97 times and there are two arrrays
these arrays change values after each iteration of the loop. so before its value changes i need to put them in a structure.For instance the structure would be something like
s(1).frame=1 %this will show the iteration no.
s(1).str=strength
s(1).freq=frequency
now i need 97 such structures say s(1) to s(97) in an array.
my question is: how can I create an array of structures within my loop. Please help me.
Upvotes: 0
Views: 97
Reputation: 12345
I like to iterate backward in cases like this, as this forces a full memory allocation the first time the loop is executed. Then the code would look something like this:
%Reset the structure
s = struct;
for ix = 97:-1:1
%Do stuff
%Store the data
s(ix).frame = ix;
s(ix).str = strength;
s(ix).freq = frequency;
end
If one frame depends on the next, or you don't know how many total frame there will be, you can scan forwards. 97 frames is not a lot of data, so you probably don;t need to worry too much about optimizing the pre-allocation portion of the problem.
%Reset the structure
s = struct;
for ix = 1:97
%Do stuff
%Store the data
s(ix).frame = ix;
s(ix).str = strength;
s(ix).freq = frequency;
end
Or, if you really need to performance of a pre-allocated array of structures, but you don't know how large it will be at the onset, you can do something like this:
%Reset the structure
s = struct;
for ix = 1:97
%Do stuff
%Extend if needed
if length(s)<ix
s(ix*2).frame = nan; %Double allocation every time you reach the end.
end
%Store the data
s(ix).frame = ix;
s(ix).str = strength;
s(ix).freq = frequency;
end
%Clip extra allocation
s = s(1:ix);
Upvotes: 2