Alternatives for concise representation of conditional statements
Show older comments
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 Comments
madhan ravi
on 5 Dec 2018
Can you explain what you are trying to acheive?
Rik
on 5 Dec 2018
Your example is a bit too basic to see what function would help here. Maybe you're looking for ismember?
Deepa Maheshvare
on 5 Dec 2018
John D'Errico
on 5 Dec 2018
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
on 5 Dec 2018
Looks like I was too late. ;-) You came to the same conclusion by the time I finished writing my response.
Deepa Maheshvare
on 5 Dec 2018
Edited: Deepa Maheshvare
on 5 Dec 2018
Accepted Answer
More Answers (0)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!