Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab conditional assignment [duplicate]

Tags:

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?

like image 923
shahar_m Avatar asked Jun 20 '11 09:06

shahar_m


2 Answers

For numeric arrays, there is another solution --

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

becomes

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

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

Advantage:

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

Warning:

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?

like image 80
Sanjay Manohar Avatar answered Oct 19 '22 21:10

Sanjay Manohar


One line conditional assignment:

a(a > 5) = 2;

This is an example of logical indexing, a > 5 is a logical (i.e. Boolean or binary) matrix/array the same size as a with a 1 where ever the expression was true. The left side of the above assignment refers to all the positions in a where a>5 has a 1.

b = a > 5; % if a = [9,3,5,6], b = [1,0,0,1]
a(~b) = 3;
c = a > 10;
a(b&c) = ...

Etc...you can do pretty much anything you'd expect with such logical arrays.

like image 24
reve_etrange Avatar answered Oct 19 '22 22:10

reve_etrange