Alternatives for concise representation of conditional statements

6 ビュー (過去 30 日間)
Deepa Maheshvare
Deepa Maheshvare 2018 年 12 月 5 日
回答済み: Steven Lord 2018 年 12 月 5 日
I have the following code with multiple conditional statements . Could someone suggest if there is a consice way of writing the same code? I'm looking for suggestions that can simply the if- elseif statements.
Number = 1:10
Value = [1 2 2 3 1 4 4 5 2 3]
UniqueValue = unique(Value)
for Num = Number
Val = Value(Num)
if Val == UniqueValue(1)
disp(Val+Val-1)
elseif Val == UniqueValue(2)
disp(Val+Val-1)
elseif Val == UniqueValue(3)
disp(Val+Val-1)
elseif Val == UniqueValue(4)
disp(Val+Val-1)
else
disp(Val+Val-1)
end
end
  6 件のコメント
John D'Errico
John D'Errico 2018 年 12 月 5 日
Looks like I was too late. ;-) You came to the same conclusion by the time I finished writing my response.
Deepa Maheshvare
Deepa Maheshvare 2018 年 12 月 5 日
編集済み: Deepa Maheshvare 2018 年 12 月 5 日
Hey John,
Thanks :) In trying to answer to the comments , I realised I asked a silly question.

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

採用された回答

Steven Lord
Steven Lord 2018 年 12 月 5 日
You've answered your specific question, but if you encounter similar code constructs in the future (needing to check whether something is a member of a finite set of options without a potentially long series of nested if / elseif / else statements) consider ismember (as Rik suggested) or a switch / case statement.

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by