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

5 views (last 30 days)
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!
  5 Comments
Andi
Andi on 10 Oct 2022
Edited: Andi on 10 Oct 2022
@KSSV becsue i know for few interation if condition satisify and for few not. Whereas, i did not get any output.
For exmaple when kk=9, the dimensions are equal but still there is no output
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
and when i delete if condition i get output :
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),:);
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
Ghazwan
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.

Sign in to comment.

Accepted Answer

Andi
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

More Answers (1)

Allen
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 Programming in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!