I'm trying to trigger a condition if a variable meets one of two values. I'm aware I can express this as:
if x == 5 || x == 6
execute code...
end
But I was wondering if there was something a bit more elegant in case x
has a long name. Something like:
if x == {5, 6}
execute code...
end
Anyone have any ideas?
Indeed there is a general approach. You can use the any
function to test if x
is equal to any of the elements of the array:
if any(x == [5, 6])
% execute code
end
This works for numerical arrays. If you’re dealing with cell arrays, you can use ismember
(thanks @ nilZ0r!)
choices = {'foo', 'bar', 'hello'};
x = 'hello';
if ismember(x, choices)
% execute code
end
ismember
works for both numerical and cell arrays (thanks @TasosPapastylianou).
A switch-case
environment would be an elegant choice:
switch x
case {5,6}
x.^2
case {7,8}
x.^4
otherwise
x.^3
end
works for strings as well:
switch x
case {'foo','bar'}
disp(x)
otherwise
disp('fail.')
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With