向量化“for”循环

发布于 2024-12-20 18:03:07 字数 279 浏览 4 评论 0原文

这段代码按照我想要的方式工作,但是本着良好的 MATLAB 代码的精神,有没有一种方法可以对其进行向量化(之前是 akx 1 向量):

start = zeros(k,1);
for i = 2:length(previous)
    if (previous(i-1) == -1)
        start(previous(i))= start(previous(i))+1;
    end    
end

一般来说,什么是对代码进行向量化的直观方法MATLAB?

This piece of code works as I want it to, but in the spirit of good MATLAB code, is there a way to vectorize this (previous is a k x 1 vector):

start = zeros(k,1);
for i = 2:length(previous)
    if (previous(i-1) == -1)
        start(previous(i))= start(previous(i))+1;
    end    
end

What, in general, is the intuitive way to go about vectorizing code in MATLAB?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

街角卖回忆 2024-12-27 18:03:07

使用 MATLAB 中的 find 命令,该命令返回向量为 TRUE 的索引 (i)。所以:

% precache indices i where previous(i-1) == 1
idx = find(previous==-1)+1;
start(previous(idx)) = start(previous(idx))+1;

我预缓存 idx 的原因是,如果 previous 是一个大向量,并且执行 find 需要一段时间。否则你可以这样做

start( find(previous==-1)+1 ) = start( find(previous==-1) ) + 1;

Use the find command in MATLAB, which returns the index (i) for which a vector is TRUE. So:

% precache indices i where previous(i-1) == 1
idx = find(previous==-1)+1;
start(previous(idx)) = start(previous(idx))+1;

The reason I precache idx is in case that previous is a big vector and doing the find takes a while. Otherwise you could just do

start( find(previous==-1)+1 ) = start( find(previous==-1) ) + 1;
王权女流氓 2024-12-27 18:03:07

您可以在不使用 find 的情况下执行此操作,以获得最佳性能:

I = [false; previous(1:end-1) == -1];
idx = previous(I);
start(idx) = start(idx) + 1;

这还可以避免 previous(end) == -1 的风险,这会导致索引超出范围替代方案中的错误。

请注意,如果 idx 包含重复索引,则其工作方式与原始索引不同。

You can do this without find, for maximum performance:

I = [false; previous(1:end-1) == -1];
idx = previous(I);
start(idx) = start(idx) + 1;

This also avoids the risk that previous(end) == -1, which would cause an index out-of-range error in the alternative.

Note that this doesn't work the same as your original if idx contains duplicated indices.

客…行舟 2024-12-27 18:03:07

我会做类似的事情:

prev_is_minus1 = [false; previous(1:end-1)==-1]
start = accumarray(previous(prev_is_minus1), 1, k)

我相信这与您发布的代码循环具有相同的效果。

I would do something like:

prev_is_minus1 = [false; previous(1:end-1)==-1]
start = accumarray(previous(prev_is_minus1), 1, k)

I believe this has the same effect as the code loop you posted.

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