将for循环转换为矢量(矢量化) [英] Convert a for loop into a vector (vectorization)
本文介绍了将for循环转换为矢量(矢量化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
%定义:
%A大小(n,1)
%B大小(n,m)
%C大小(n, 1)
B = [2 200; 3 300; 4 400];
C = [1; 2; 1]; $ j
对于j = 1:n
A(j)= B(j,C(j));
end
所以要清楚的是,有没有其他的方式来表示A,函数的B和C,而不必写一个循环?
解决方案
是的,有:
A = B(sub2ind([n,m],(1:n)。',C));
For those super experts out there, I was wondering if you see a quick way to convert the following "for" loop into a one-line vector calculation that is more efficient.
%Define:
%A size (n,1)
%B size (n,m)
%C size (n,1)
B = [2 200; 3 300; 4 400];
C = [1;2;1];
for j=1:n
A(j) = B( j, C(j) );
end
So to be clear, is there any alternative way to express A, as a function of B and C, without having to write a loop?
解决方案
Yes, there is:
A = B(sub2ind([n,m], (1:n).', C));
这篇关于将for循环转换为矢量(矢量化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文