How to include several conditions in one equivalence operator?

I am trying to call a condition if a variable matches one of two values. I know that I can express it as:

if x == 5 || x == 6 execute code... end 

But I was wondering if there is something more elegant if x has a long name. Sort of:

 if x == {5, 6} execute code... end 

Does anyone have any ideas?

+5
source share
2 answers

Indeed, there is a general approach. You can use the any function to check if x matches any of the elements in the array:

 if any(x == [5, 6]) % execute code end 

This works for numeric arrays. If you are working 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 numeric and array of cells (thanks @TasosPapastylianou).

+6
source

A switch-case would be an elegant choice:

 switch x case {5,6} x.^2 case {7,8} x.^4 otherwise x.^3 end 

works for strings too:

 switch x case {'foo','bar'} disp(x) otherwise disp('fail.') end 
+3
source

Source: https://habr.com/ru/post/1263380/


All Articles