向量化"for"循环 [英] Vectorizing 'for' loops
本文介绍了向量化"for"循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这一段代码可以按我的意愿工作,但是根据良好的MATLAB代码的精神,有一种方法可以对此进行矢量化(以前是k x 1矢量):
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
通常,在MATLAB中进行矢量化代码的直观方法是什么?
What, in general, is the intuitive way to go about vectorizing code in MATLAB?
推荐答案
您可以在没有find
的情况下执行此操作,以实现最佳性能:
You can do this without find
, for maximum performance:
I = [false; previous(1:end-1) == -1];
idx = previous(I);
start(idx) = start(idx) + 1;
这还避免了previous(end) == -1
的风险,该风险会导致替代项中的索引超出范围错误.
This also avoids the risk that previous(end) == -1
, which would cause an index out-of-range error in the alternative.
请注意,如果idx
包含重复的索引,则此功能与原始功能不同.
Note that this doesn't work the same as your original if idx
contains duplicated indices.
这篇关于向量化"for"循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文