向量化 if 在 matlab 中
我有一个布尔数组,称之为flag
。
我有两个数值数组 ifTrue
、ifFalse
。所有这些数组的大小相同,出于此问题的目的,假设这些数组中的每个元素都是唯一的。
我想要一个具有以下属性的函数 g
a = g(flag, ifTrue, ifFalse)
all(flag == (a == ifTrue))
all(~flag == (a == ifFalse))
或者用英语,我希望 g
在 flagifTrue
元素code> 为 true,当 flag
为 false 时为 ifFalse
元素。
或者,在 matlab 中,我可以使用循环来做到这一点:
a = zeros(size(ifTrue));
for i = 1 : numel(ifTrue);
if flag(i)
a(i) = ifTrue(i)
else
a(i) = ifFalse(i)
end
end
Is there a vectorized method?
谢谢
I have a boolean array call it flag
.
I have two numeric arrays ifTrue
, ifFalse
. All these arrays are the same size, For purposes of this question assume every element in these arrays is unique.
I would like a function g
with the property that
a = g(flag, ifTrue, ifFalse)
all(flag == (a == ifTrue))
all(~flag == (a == ifFalse))
Or in English, I would like g
to return ifTrue
elements when flag
is true, and ifFalse
elements when flag
is false.
Or, in matlab, I could do this with loops:
a = zeros(size(ifTrue));
for i = 1 : numel(ifTrue);
if flag(i)
a(i) = ifTrue(i)
else
a(i) = ifFalse(i)
end
end
Is there a vectorized approach?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设 flag 包含 1 表示 true,0 表示 false 元素:
a = flag .* ifTrue + (1 - flag) .* ifFalse;
Assuming that flag contains ones for true, and zeros for false elements:
a = flag .* ifTrue + (1 - flag) .* ifFalse;