# Storing values from inside the third loop to a variable outside the loops

2 views (last 30 days)
Mathan on 14 May 2022
Commented: Mathan on 15 May 2022
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
Mathan on 14 May 2022
Hi,
Well actually no - sorry if my second example was confusing. I have modified the original question now with a more suitable example which shows that the c matrix changes its value during the loop run and is a random matrix, so infact I really cannot use the repmat(). What I was looking for was a way to append the values from c matrix to final_data as rows without overriding the values.

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
c = 3×8
0.7756 0.0228 0.8194 0.5967 0.9381 0.2879 0.0092 0.5636 0.6957 0.2733 0.8883 0.8130 0.1560 0.2556 0.6728 0.6247 0.6122 0.4209 0.3791 0.1853 0.5323 0.5289 0.8371 0.9574
c = 3×8
0.3283 0.4400 0.7155 0.8591 0.2053 0.6418 0.8155 0.1471 0.0725 0.2098 0.3402 0.0290 0.3501 0.8085 0.3803 0.9335 0.2055 0.6950 0.4742 0.4666 0.6381 0.4812 0.3803 0.6402
c = 3×8
0.0360 0.5393 0.2289 0.1805 0.0598 0.8810 0.8914 0.7146 0.7247 0.0987 0.1058 0.2307 0.6649 0.0273 0.8709 0.4841 0.1058 0.6794 0.2373 0.1903 0.3412 0.3625 0.4358 0.4167
c = 3×8
0.2973 0.0796 0.7687 0.6992 0.1326 0.6452 0.0892 0.1665 0.4848 0.9148 0.6581 0.6309 0.0303 0.6834 0.3425 0.4914 0.7989 0.3075 0.1044 0.1785 0.6989 0.8545 0.1679 0.0347
disp(final_data)
0.7756 0.3283 0.0360 0.2973 0.6957 0.0725 0.7247 0.4848 0.6122 0.2055 0.1058 0.7989 0.0228 0.4400 0.5393 0.0796 0.2733 0.2098 0.0987 0.9148 0.4209 0.6950 0.6794 0.3075 NaN 0.7155 0.2289 0.7687 NaN 0.3402 0.1058 0.6581 NaN 0.4742 0.2373 0.1044 NaN 0.8591 0.1805 0.6992 NaN 0.0290 0.2307 0.6309 NaN 0.4666 0.1903 0.1785 NaN NaN 0.0598 0.1326 NaN NaN 0.6649 0.0303 NaN NaN 0.3412 0.6989 NaN NaN 0.8810 0.6452 NaN NaN 0.0273 0.6834 NaN NaN 0.3625 0.8545 NaN NaN NaN 0.0892 NaN NaN NaN 0.3425 NaN NaN NaN 0.1679 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Mathan on 15 May 2022
Thank you.