Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include multiple conditions in one equivalence statement?

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?

like image 364
jshep Avatar asked Jan 26 '17 09:01

jshep


2 Answers

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).

like image 56
Lumen Avatar answered Nov 04 '22 10:11

Lumen


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
like image 37
Robert Seifert Avatar answered Nov 04 '22 10:11

Robert Seifert