How to use for loop inside switch case?

2 ビュー (過去 30 日間)
Md Abu Talhamainuddin Ansary
Md Abu Talhamainuddin Ansary 2017 年 9 月 27 日
回答済み: Rik 2017 年 9 月 27 日
How can I use for loop inside switch cases? For example
for j=1,2,...,m
switch j
case 1,2,...,m-1
y=x(j);
case m
y=x(m)^2;
end
What is exact MATLAB coding?
  1 件のコメント
Stephen23
Stephen23 2017 年 9 月 27 日
Your example would be best solved using if or some indexing.

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

回答 (1 件)

Rik
Rik 2017 年 9 月 27 日
If you really insist on a for-loop, you can use curly brackets. Most times there will be a better solution for this, which will increase speed quite a bit compared to a for-loop.
for a=1:4
switch a
case {1,3}
disp('1 or 3')
otherwise
fprintf('%d\n',a)
end
end
Will print:
1 or 3
2
1 or 3
4

カテゴリ

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