Matlab条件赋值 [英] Matlab conditional assignment
问题描述
我正在寻找与c#condition ? true-expression : false-expression
条件赋值等效的Matlab.我最了解的是a = 5>2
,这是true \ false的赋值,
但是是否有任何一行条件分配
if condition a=1;else a=2; end
?
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
?
推荐答案
一行条件赋值:
a(a > 5) = 2;
这是逻辑索引的一个示例,a > 5
是大小与a
相同且带有1
的逻辑(即布尔或二进制)矩阵/数组,只要表达式为真.上面分配的左侧是a
中a>5
具有1
的所有位置.
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条件赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!