开发者

Matlab conditional assignment [duplicate]

This question already has answers here: 开发者_StackOverflow社区 Is there a Matlab conditional IF operator that can be placed INLINE like VBA's IIF (10 answers) Closed 9 years ago.

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:

  • 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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜