# How to store the output of multiple for loops in an empty matrix in a particular order?

1 view (last 30 days)
Andi on 26 Oct 2022
Edited: Andi on 26 Oct 2022
Hi everyone,
My script consists of 2 loops with multiple conditions. For each iteration, I get an output that consists of 3 rows and 4 columns. I want to save this output in an empty matrix in sequential order. May someone suggest how I can do this?
Here is my attempt
T=[]
for kk=1:2
s2=t_d(t_d(:,1)>= CE_L(kk) & t_d(:,1)<= CE_M(kk),:);
s1=v_d(v_d(:,1)>= CE_L(kk) & v_d(:,1)<= CE_M(kk),:);
for i=0:1:3;
% multiple missing step to make the probelm simple
ww=1:length(tzcd);
ph=abs(phz);
phase=mean(ph);
med=median(ph);
st=std(ph);
obb=i;
res=[i phase med st];
TT=[TT,res];
end
end
However this save outpout as an array, whereas i need as a matrix. My output is looks like this
0.0 166.1 167.0 2.3
1.0 169.5 166.4 11.0
2.0 160.8 162.9 5.7
3.0 157.6 151.7 21.1
for each iteration of kk loop, where as each row represent the output of i iteration.

Alex Hanes on 26 Oct 2022
Edited: Alex Hanes on 26 Oct 2022
After each iteration of your for loop over i (for i=0:1:3 ... ), you replace the array, TT, that stores everything sequentially. Consider pre-allocating an array for TT and update after each loop, as you are already doing:
nk = 2; % number of iterations in your kk-loop
ni = 4; % number of iterations in your i-loop
nc = 4; % number of columns from your 'res' each loop
TT = zeros(nk*ni,nc); % pre-allocate
Now, instead of having TT = [TT,res]; in your code, replace it with:
for kk = 1:nk
for ii = 0:1:ni-1
% Stuff
idx = (kk-1)*ni + ii + 1; % calculate index
TT(idx,:) = res;
end
end
Andi on 26 Oct 2022
Edited: Andi on 26 Oct 2022
@Alex Hanes thank you! but it still only stored results from last iteration. ### Categories

Find more on Vibration Analysis 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!