ternary operator in matlab

2019-01-18 02:08发布

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

7条回答
来,给爷笑一个
2楼-- · 2019-01-18 02:38

You can do

var = 5 > 4;

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-18 02:51

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

查看更多
Viruses.
4楼-- · 2019-01-18 02:55

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.

查看更多
别忘想泡老子
5楼-- · 2019-01-18 02:55

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.

查看更多
别忘想泡老子
6楼-- · 2019-01-18 02:55

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

查看更多
成全新的幸福
7楼-- · 2019-01-18 02:58

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.

查看更多
登录 后发表回答