Storing values from inside the third loop to a variable outside the loops
2 views (last 30 days)
Show older comments
Hi all,
Is it possible to store values from the inside of a third for loop into a variable which is outside the loops? For instance I have this code:
a = 2:1:5;
b = [1 1.2 2 2.3 3 3.3 4 5];
final_data = [];
for ii=1:length(a)
c = rand(3,8);
for jj=1:length(b)
c_data = c(:,jj);
if (a(ii) > b(jj) )
for xx = 1:length(c_data)
final_data(xx,ii) = c_data(xx);
end
end
end
end
and I want the values in 'c_data' to be stored inside 'final_data' as rows (the columns are determined by the value of ' ii ' ) for every 'jj' value. But it so happens that the values get over-written for every ' jj ' loop iteration. Or in other words, I was looking for a way to vertically append c_data to final_data for every jj loop iteration without being overwritten.
Thanks
Accepted Answer
Voss
on 14 May 2022
Maybe something like this?
a = 2:1:5;
b = [1 1.2 2 2.3 3 3.3 4 5];
na = numel(a);
nb = numel(b);
nc = 3;
final_data = NaN(nb*nc,na);
for ii=1:na
c = rand(nc,nb) % showing c on command-line for reference
for jj=1:nb
if (a(ii) > b(jj))
final_data((jj-1)*nc+(1:nc),ii) = c(:,jj);
end
end
end
disp(final_data)
5 Comments
Voss
on 15 May 2022
You can avoid having any NaNs above any non-NaN c values by keeping track of how many rows have been written to in each column:
a = 2:1:5;
% b = [1 1.2 2 2.3 3 3.3 4 5];
b = [1 1.2 4 5 3 3.3 2 2.3];
na = numel(a);
nb = numel(b);
nc = 3;
final_data = NaN(nb*nc,na);
last_row = zeros(1,na);
for ii=1:na
c = rand(nc,nb) % showing c on command-line for reference
for jj=1:nb
if (a(ii) > b(jj))
final_data(last_row(ii)+(1:nc),ii) = c(:,jj);
last_row(ii) = last_row(ii)+nc;
end
end
end
disp(final_data);
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!