# How to use if condition inside for loop without breaking the loop?

1 view (last 30 days)
Andi on 10 Oct 2022
Answered: Allen on 10 Oct 2022
Hi everyone,
I have review many post related to use of if loop inside loop in such a way that if did not influnec the runing loop. However, i am facing probelm while implementing the same approach.
Here os waht i attempt so far:
for kk=2:3
s1=t_d(t_d(:,1)>= CE_L(kk) & t_d(:,1)<= CE_U(kk),:);
s2=v_d(v_d(:,1)>= CE_L(kk) & v_d(:,1)<= CE_U(kk),:);
if length(s1) == length(s2)
continue
S=[s1 s2];
t=S(:, 1);
t=(t-t(1)); %time (days) (initial offset removed)
ser1=S(:, 2)-mean(S(:,2)); % series 1 minus its mean
ser2=S(:, 4)-mean(S(:,4)); % series 2 minus its mean
end
end
However, my for loop stop working when if condition not satisified. Whereas, I want my for loop move to next iteration, but i didn't. May somene suggest how can i fix this.
Thank you!
Ghazwan on 10 Oct 2022
The structure of for loop of Torsten is correct. The issue you are having may be related to the data. Perhaps you need to practice the for-loop-continue structure on simpler matrices first.

Andi on 10 Oct 2022
for kk=9:9
s1=t_d(t_d(:,1)>= CE_L(kk) & t_d(:,1)<= CE_U(kk),:);
s2=v_d(v_d(:,1)>= CE_L(kk) & v_d(:,1)<= CE_U(kk),:);
if length(s1) ~= length(s2)
continue
end
S=[s1 s2];
t=S(:, 1);
t=(t-t(1)); %time (days) (initial offset removed)
ser1=S(:, 2)-mean(S(:,2)); % series 1 minus its mean
ser2=S(:, 4)-mean(S(:,4)); % series 2 minus its mean
end

Allen on 10 Oct 2022
@Adnan Barkat, it appears that your for-loop is functioning properly. However, you appear to be overwriting ser1 and ser2 during each iteration of the loop, which is returning only a single result from the last instance the loop runs.

### Categories

Find more on Loops and Conditional Statements 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!