MATLAB Answers

0

Alternatives for concise representation of conditional statements

Asked by Deepa Maheshvare on 5 Dec 2018
Latest activity Answered by Steven Lord
on 5 Dec 2018
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

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.
Looks like I was too late. ;-) You came to the same conclusion by the time I finished writing my response.
Hey John,
Thanks :) In trying to answer to the comments , I realised I asked a silly question.

Sign in to comment.

1 Answer

Answer by Steven Lord
on 5 Dec 2018
 Accepted Answer

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 Comments

Sign in to comment.