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

8 ビュー (過去 30 日間)
Andi
Andi 2022 年 10 月 10 日
回答済み: Allen 2022 年 10 月 10 日
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 件のコメント
Andi
Andi 2022 年 10 月 10 日
編集済み: Andi 2022 年 10 月 10 日
@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 2022 年 10 月 10 日
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
Andi 2022 年 10 月 10 日
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

その他の回答 (1 件)

Allen
Allen 2022 年 10 月 10 日
@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.

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by