向量化 if 在 matlab 中

发布于 2024-12-20 23:56:24 字数 689 浏览 4 评论 0原文

我有一个布尔数组,称之为flag

我有两个数值数组 ifTrueifFalse。所有这些数组的大小相同,出于此问题的目的,假设这些数组中的每个元素都是唯一的。

我想要一个具有以下属性的函数 g

a = g(flag, ifTrue, ifFalse)

all(flag == (a == ifTrue))
all(~flag == (a == ifFalse))

或者用英语,我希望 gflagifTrue 元素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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

弃爱 2024-12-27 23:56:24
%# Given, for example:
ifTrue = 1:10
ifFalse = -ifTrue  
flag = rand(1,10) > 0.5
%# First, set 'a' to ifFalse
a = ifFalse
%# Then override the places where flag is true
a(flag) = ifTrue(flag)
%# Given, for example:
ifTrue = 1:10
ifFalse = -ifTrue  
flag = rand(1,10) > 0.5
%# First, set 'a' to ifFalse
a = ifFalse
%# Then override the places where flag is true
a(flag) = ifTrue(flag)
时光倒影 2024-12-27 23:56:24

假设 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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文