Alternatives for concise representation of conditional statements
이전 댓글 표시
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
madhan ravi
2018년 12월 5일
Can you explain what you are trying to acheive?
Rik
2018년 12월 5일
Your example is a bit too basic to see what function would help here. Maybe you're looking for ismember?
Deepa Maheshvare
2018년 12월 5일
John D'Errico
2018년 12월 5일
What are you trying to do here?
You are displaying the exact same result:
Val + Val - 1
in every case. And even when none of the cases comply, you display the same result. So what is wrong with simply
disp(2*Val - 1)
and be gone with all those cases and tests?
Or is that just a dummy statement you put in there to simplify things for your question? So if you want to simplify code, then you need to recognize that the simplification will probably result in removing all those tests.
For example, if we look at your code, it produces this set of results:
1
3
3
5
1
7
7
9
3
5
Now, suppose I did nothing more than:
2*Value - 1
ans =
1 3 3 5 1 7 7 9 3 5
What a surprise! We get identically the same thing, yet no tests, no call to unique, no complicated code, no loop at all.
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
2018년 12월 5일
편집: Deepa Maheshvare
2018년 12월 5일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!