ternary operator in matlab

is there a way of typing for if like:

var = (cond) ? true : false;

or do we have to use this format?

if (cond)
 true
else
 false
end

Answers


MatLab doesn't have a ternary operator, or any other syntactic sugar for one-line if-statements. But if your if-statement is really simple, you could just write it in one line anyway:

if (cond); casetrue(); else; casefalse(); end

It's not as simple as ternary operator, but still better than writing it in 5 lines of code.


If you only need true or false, you can do what MatlabSorter suggests. In case you want a real tertiary operator (i.e. a = b ? c : d), there is none in MATLAB. However, using the file supplied here, you can get close.


You can do

var = 5 > 4;

which will set var to true. Just substitute what ever you need for 5 > 4.


MATLAB doesn't have conditional expressions, but in some situations you can get a similar effect by saying, e.g., var = cond*true_expr + (1-cond)*false_expr. Unlike C's conditional expression, this will of course always evaluate both true_expr and false_expr, and if cond happens not to be either 0 or 1 (note: false behaves like 0; true behaves like 1) you'll get crazy results.


Hmm... no one has mentioned this

fi = @(varargin)varargin{end-varargin{1}}

somewhere in the docs it is written the `end' is coming to one so this will be more future proof

fi = @(varargin)varargin{length(varargin)-varargin{1}}

Usage :

fi(input('Do you like Matlab ? '),'yes','no')
>> no

If your in the need of inline cases see Mathworks ...


I use this style frequently:

cond = what < ever;

n = getfield([23,42], {1+(what < ever)}) % for any 1x1-data
s = cell2mat(getfield({'no','yes'}, {1+(what < ever)})) % for nonuniform

it's compact enough to not require a helper function


Replace

c = (x ? a : b)

by

c = subsref({b; a}, substruct('{}', {x + 1}))

x should be a boolean value or 1 or 0. true or 1 will select a false or 0 will select b This should work with all what cells can contain and can also be used in an intricate formular!


Need Your Help

Drawing Route Between Two Places on GMSMapView in iOS

ios google-maps ios7 google-polyline gmsmapview

I am Developing an iOS Application. In that Application i am having 2 Fields From and To. I Entered Address using Google Auto Complete API.and also i am able to Getting the Latitude and Longitude o...