フィルターのクリア

IF / ELSE Usage within For loop for Specific Iteration Only

5 ビュー (過去 30 日間)
Sam
Sam 2014 年 2 月 8 日
コメント済み: Jos (10584) 2014 年 2 月 10 日
When using a FOR LOOP can I do something like when
for i=1:1:15
When i iterates at 9, 10, 12 & 14 ONLY do an additional condition. Is it possible? Can i maybe add in an IF Condition? Would be good if i can sum up al the 4 possibilities within this 1 IF Statement. Thanks!

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 8 日
for i=1:1:15
if ismember(i,[9 10 12 14])
% do
end

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2014 年 2 月 9 日
As a follow-up, if you only need to perform the statements within a for-loop when the iterator takes specific values, you can change the expression used in the for loop.
for k = 1:10
if ismember(k, [2 5 8])
% statements here
end
end
equals
for k = [2 5 8]
% statements here
end
This neat feature of MatLabs for-loop is easily overlooked ...
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 9 日
Jos, I don't think that's what Sam asked for. He needs to do a for loop for i=1:15, but he wants to add some lines of code for specific values of i
Jos (10584)
Jos (10584) 2014 年 2 月 10 日
Yep, I know, (and that's why I posted it as a follow-up). It just serves to illustrate ML functionality when there are NO statements within the for-loop but outside the if-ismember section ...

サインインしてコメントする。


dpb
dpb 2014 年 2 月 8 日
iskp=[9 10 12 14];
j=1;
for i=1:15
if i==iskp(j) && j<=length(iskp)
j=j+1;
% do whatever else here
end
% rest here (or ahead of if if order-dependent)
...
If you can derive the condition for iskp values then you can have any other manner of generating the test as desired.
Also check out
doc switch
doc case
and friends as alternative structures that may be helpful
  1 件のコメント
Sam
Sam 2014 年 2 月 9 日
hi dpb! thanks for your answer i agree with it as well but i had went with the earlier one since it was simpler as i have a few functions i am calling for this segment of my work and i would prefer a simpler code so it will be easier to troubleshoot later..
Cheers...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by