向量化“for”循环
这段代码按照我想要的方式工作,但是本着良好的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 MATLAB 中的
find
命令,该命令返回向量为TRUE
的索引 (i
)。所以:我预缓存 idx 的原因是,如果
previous
是一个大向量,并且执行find
需要一段时间。否则你可以这样做Use the
find
command in MATLAB, which returns the index (i
) for which a vector isTRUE
. So:The reason I precache
idx
is in case thatprevious
is a big vector and doing thefind
takes a while. Otherwise you could just do您可以在不使用
find
的情况下执行此操作,以获得最佳性能:这还可以避免
previous(end) == -1
的风险,这会导致索引超出范围替代方案中的错误。请注意,如果 idx 包含重复索引,则其工作方式与原始索引不同。
You can do this without
find
, for maximum performance: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.我会做类似的事情:
我相信这与您发布的代码循环具有相同的效果。
I would do something like:
I believe this has the same effect as the code loop you posted.