Storing data from FOR loops

2 views (last 30 days)
Good evening,
I have encountered a problem regarding data storing from FOR loops. I'm using the following code:
[~,m]=size(obs);
for j=1:m;
[~,n]=size(obs(j).data);
for i=1:n
A=extr(eph,obs(j).data(1,i));
B(i).data=A;
end
end
% obs is a 1x2880 structure
% eph is a 36x212 matrix
% extr(eph,obs.data) is a function
% I want to store all values of B(i) in a new structure (1x2880)
The problem is that my code remembers the previous stored data and adds the new data in the current structure..How I can manage this situation?

Accepted Answer

Geoff Hayes
Geoff Hayes on 4 Sep 2014
Ciuban - you somehow need to use your j when updating B so that you don't overwrite previously stored data with the data from the current iteration. You could try creating a cell array of the structures as
[~,m]=size(obs);
% create an array for the structs
allData = cell(1,m);
for j=1:m;
[~,n]=size(obs(j).data);
% size B appropriately
B = repmat(struct('data',[]),1,n);
for i=1:n
A=extr(eph,obs(j).data(1,i));
B(i).data=A;
end
% assign B to allData
allData{j} = B;
end
At each iteration, the code "resets" B given the number of columns in the jth observation data vector. At the end of the inner for loop, we just assign B to the jth element of the allData cell array. Once completed, allData is a 1x2880 cell array of structures.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!