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
?
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:
X
and Y
are equal in sizeWarning:
Doesn't work gracefully with NaN
s. 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With