How to make the last iteration of a for loop run differently?

72 visualizzazioni (ultimi 30 giorni)
Hi there,
I've written a for loop that averages and processes column of data focussing sequentially on 7200 rows at a time. To automate this, I used an index variable that is the total size of the column of the data/7200. I will be using this loop to process many different columns of data, some of which do not divide perfectly by 7200. In this case I want the for loop to process as many sets of 7200 as it can, but for the last iteration, do the calculations for the remainder of the rows (<7200). However, the way my script is laid out doesnt allow this and I am unsure of what I can use to do this. I am still fairly new to matlab so trying to wrap my head around my things.
To explain further, I want pt1, pt2 and pt3 to refer to the remainder of the data on the last iteration of the for loop, not necessarily 7200.
PT1 = test.sdata.PT1;
number = size(PT1,1)/7200; %Divides the size of the data by 7200
Z1_pt1 = 99;
Z1_pt2 = 105.83;
Z1_pt3 = 99;
Z2 = 0;
DT = 0.125;
for i = 1:number
j = i * 7200;
k = j - 7199;
pt1 = test.sdata.PT1(k:j,:); % reads the data at the correct points 1:7200, 7201:14400 etc etc
pt2 = test.sdata.PT2(k:j,:);
pt3 = test.sdata.PT3(k:j,:);
h1 = Z1_pt1 + (mean(pt1));
h2 = Z1_pt2 + (mean(pt2));
h3 = Z1_pt3 + (mean(pt3));
pt1out(:,i) = u_depth_xform(pt1,Z1_pt1,Z2,h1,DT); % Outputs the data in seperate colums for each 15 minute section
pt2out(:,i) = u_depth_xform(pt2,Z1_pt2,Z2,h2,DT); % Outputs the data in seperate colums for each 15 minute section
pt3out(:,i) = u_depth_xform(pt3,Z1_pt3,Z2,h3,DT); % Outputs the data in seperate colums for each 15 minute section
end

Risposta accettata

Simon Allosserie
Simon Allosserie il 26 Feb 2021
You can do something like this
for i = 1:number
% do the things that have to happen for each iteration
if i < thelastiteration
%do the things that don't have to happen for the last iteration
else %this will only be called in the last iteration
%do the special thing for the last iteration
end
end

Più risposte (1)

Stephen23
Stephen23 il 26 Feb 2021
Modificato: Stephen23 il 26 Feb 2021
It is simpler to just adjust the indices automatically, no IFs required:
nmr = size(PT1,1)
grp = 7200;
nmg = ceil(nmr/grp);
..
for ii = 1:nmg
idb = 1+(ii-1)*grp; % begin group
ide = min(nmr,ii*grp); % end group
idx = idb:ide;
%
pt1 = test.sdata.PT1(idx,:);
... etc
end

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by