# Storing and passing all iterations to an array outside the nested for loops

1 view (last 30 days)
Banjo on 23 Dec 2019
Edited: Banjo on 23 Dec 2019
Hello, my problem is basically that I don't know how to store and pass all 8736 different values from L(k) to the outside of nested for loops in a form of an array (8736x1), so I can use it for further processing and comparing with some other arrays in my code. Code is below...
Lw =[52x1]; Ld=[7x1]; Lh=[24x6]; Ly=number;
for i=1:length(Lw)
for j=1:length(Ld)
for k=1:length(Lh)
if ((i>=1 && i<=8)||(i>=44 && i<=52))
if (j>=1 && j<=5)
L(k)=Lw(i)*Ld(j)*Lh(k,1)*Ly;
else
L(k)=Lw(i)*Ld(j)*Lh(k,2)*Ly;
end
end
if (i>=18 && i<=30)
if (j>=1 && j<=5)
L(k)=Lw(i)*Ld(j)*Lh(k,3)*Ly;
else
L(k)=Lw(i)*Ld(j)*Lh(k,4)*Ly;
end
end
if (i>=9 && i<=17)||(i>=31 && i<=43)
if (j>=1 && j<=5)
L(k)=Lw(i)*Ld(j)*Lh(k,5)*Ly;
else
L(k)=Lw(i)*Ld(j)*Lh(k,6)*Ly;
end
end
L(k)
end
end
end
L to be passed here with all 8736 values

per isakson on 23 Dec 2019
Edited: per isakson on 23 Dec 2019
Read Multidimensional Arrays carefully and then try (which implements the advise of Image Analyst)
>> clearvars
>> cssm
>> sum(double(isnan(L(:))))
ans =
0
>> numel(L)
ans =
8736
>>
where the script, cssm, is your script with a few modifications
%% cssm
Lw = rand(52,1); Ld=rand(7,1); Lh=rand(24,6); Ly = 17;
L = nan( length(Lw), length(Ld), length(Lh) ); % pre-allocate
for ii=1:length(Lw)
for jj=1:length(Ld)
for kk=1:length(Lh) % size(Lh,1) (if that's what you intend) is better
if ((ii>=1 && ii<=8)||(ii>=44 && ii<=52))
if (jj>=1 && jj<=5)
L(ii,jj,kk)=Lw(ii)*Ld(jj)*Lh(kk,1)*Ly;
else
L(ii,jj,kk)=Lw(ii)*Ld(jj)*Lh(kk,2)*Ly;
end
end
if (ii>=18 && ii<=30)
if (jj>=1 && jj<=5)
L(ii,jj,kk)=Lw(ii)*Ld(jj)*Lh(kk,3)*Ly;
else
L(ii,jj,kk)=Lw(ii)*Ld(jj)*Lh(kk,4)*Ly;
end
end
if (ii>=9 && ii<=17)||(ii>=31 && ii<=43)
if (jj>=1 && jj<=5)
L(ii,jj,kk)=Lw(ii)*Ld(jj)*Lh(kk,5)*Ly;
else
L(ii,jj,kk)=Lw(ii)*Ld(jj)*Lh(kk,6)*Ly;
end
end
end
end
end

Image Analyst on 23 Dec 2019
Banjo, also take note of the nice change he made to change the variable names from i to ii and j to jj because i and j also function as the imaginary variable in MATLAB so we recommend to NOT use i and j as variable names.
Banjo on 23 Dec 2019
Thank you both!! I also used reshape at the end, but anyhow I made it to work.

Image Analyst on 23 Dec 2019
Edited: Image Analyst on 23 Dec 2019
L is available after all the loops terminate. It does not exist solely inside the loop and then vanish when the loops end. Simply pass L to your other code for further processing.
If you don't want to overwrite L on the inner loop, simply add additional indexes L(i, j, k).