Changing the For LOOP conditions

5 ビュー (過去 30 日間)
Jason
Jason 2019 年 10 月 10 日
コメント済み: Jason 2019 年 10 月 10 日
Hello.
I have a for loop that starts with image number 1 and ends with the last image n.
for i=1:n
Sometimes, I only need to analyse every other image- starting at image 2, so would require
for i=2:2:n
I would like to use a checkbox to determine the parameters of the loop.
Rather than write out 2 different loops depending on the value of a checkbox, is there a way where i can just use a single for loop with some condition at the start
i.e.
val=get(handles.checkbox1,'Value)
if val==1
use i=1:n
else
use i=2:2:n
end

採用された回答

Shubham Gupta
Shubham Gupta 2019 年 10 月 10 日
編集済み: Shubham Gupta 2019 年 10 月 10 日
One of the way to do this is define the for loop conditions using predefined vectors.
You can write vector to set how the for loop varies. For e.g.
Vec = 1:10
for i = Vec
printf('%d',i)
end
Now, you just need to set Vec according the checkbox :
val=get(handles.checkbox1,'Value')
Vec1 = 1:n;
Vec2 = 2:2:n;
if val==1
Vec = Vec1;
else
Vec = Vec2;
end
for i = Vec
% operation
end
  1 件のコメント
Jason
Jason 2019 年 10 月 10 日
Perfect, thankyou

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

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 10 月 10 日
編集済み: Stephen23 2019 年 10 月 10 日
If val has a value either 1 or 2:
for k = 1:val:n
If val is a boolean (i.e. 0 or 1) then simply do either of these:
for k = 1:(1+val):n % true->2, false->1
for k = 1:(2-val):n % true->1, false->2
  3 件のコメント
Stephen23
Stephen23 2019 年 10 月 10 日
編集済み: Stephen23 2019 年 10 月 10 日
"But also the starting value needs to be 1 or 2."
That is such a trivially simple change, that I sure that you could have figured that out yourself:
for k = val:val:n
And for the boolean you can also do it quite simply. Using if is a waste of MATLAB, when you can simply set the step size directly. Using intermediate vectors is also pointless.
Jason
Jason 2019 年 10 月 10 日
Ok, i will use this approach. Thanks

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

カテゴリ

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