Matlab conditional assignment


I'm looking for Matlab equivalent of c# condition ? true-expression : false-expression conditional assignment. The most I know of is a = 5>2, which is true\false assignment,
but is there any one line conditional assignment for
if condition a=1;else a=2; end?

Best Solution

For numeric arrays, there is another solution --

// C: 
A = COND ? X : Y;


% A, X and Y are numerics 
% COND is a logical condition.

A = COND.*X + (~COND).*Y ;


works wonderfully in parallel for vectors or large arrays - each item in A gets assigned depending on the corresponding condition. The same line works for:

  • condition is scalar, arrays X and Y are equal in size
  • condition is an array of any size, X and Y are scalars
  • condition and X and Y are all arrays of the same size


Doesn't work gracefully with NaNs. Beware! If an element of X is nan, or an element of Y is nan, then you'll get a NaN in A, irrespective of the condition.

Really Useful corollary:

you can use bsxfun where COND and X/Y have different sizes.

A = bsxfun( @times, COND', X ) +  bsxfun( @times, ~COND', Y );

works for example where COND and X/Y are vectors of different lengths.

neat eh?

Related Question