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
?

- 3,461
- 5
- 41
- 61
-
1Awfully close to being a duplicate of this: [if-statement in matlab](http://stackoverflow.com/q/5594937/52738) You may find some of the answers there helpful. – gnovice Jun 20 '11 at 14:56
3 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
andY
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 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?

- 6,920
- 3
- 35
- 58
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.

- 2,561
- 1
- 22
- 36
-
2is it possible to put in an else? - to assign something in both cases? Like: a (b&c) = 1 : 0; – skofgar Aug 17 '12 at 08:58
-
1@skofgar The only way to that is with two lines: `a(b&c) = 1;` and `a(b~=c) = 0;` or `a(xor(b,c)) = 0`. – reve_etrange Aug 21 '12 at 19:58
-
-
An array of logical (boolean) values, with each element holding the output of the conditional for the corresponding element in `a`. Think of it as a binary 'mask' over `a` indicating where `a` contains a value greater than 5. Updated with a little comment. – reve_etrange Feb 20 '15 at 02:47
-
What does it say? Assign `2` to `a` if condition is true, else do nothing? – lolelo Jul 03 '20 at 15:35
Matlab does not have a ternary operator. You though easily write a function that will do such thing for you:
function c = conditional(condition , a , b)
if condition
c = a;
else
c = b;
end
end

- 12,549
- 13
- 64
- 114