Convert a for loop into a vector (vectorization)

做~自己de王妃 提交于 2019-12-31 03:43:09

问题


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?


回答1:


Yes, there is:

A = B(sub2ind([n,m], (1:n).', C));



回答2:


It depends on functions A, B, and C, but this might work:

j = 1:n;
A = B(j, C(j));


来源:https://stackoverflow.com/questions/19122715/convert-a-for-loop-into-a-vector-vectorization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!