## Alternatives for concise representation of conditional statements

### Deepa Maheshvare (view profile)

on 5 Dec 2018
Latest activity Answered by Steven Lord

on 5 Dec 2018

### Steven Lord (view profile)

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

John D'Errico

### John D'Errico (view profile)

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

### John D'Errico (view profile)

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

### Deepa Maheshvare (view profile)

on 5 Dec 2018
Hey John,
Thanks :) In trying to answer to the comments , I realised I asked a silly question.