How to vectorize this code?
显示 更早的评论
Hi all,
I need to vectorize the following code in order to make it faster:
ar=[ 115 139 168;
133 160 193;
155 187 226];
at=[ 803 667 552;
3212 2667 2208;
5621 4667 3864];
afr(:,:,1)=[0 17 3;
4 3208 29;
6 127 12];
afr(:,:,2)= [0 0 0;
0 14 2;
0 3 2];
afr(:,:,3)=[0 0 0;
0 4 1;
0 1 0];
here my code with nested loop:
[Sar Iar]=sort(reshape(ar,1,prod(size(ar))));
[Sat Iat]=sort(reshape(at,1,prod(size(at))));
Output=zeros(prod(size(ar)),prod(size(at)));
for i=1:length(afr(1,1,:))
for j=1:length(afr(1,:,1))
for k=1:length(afr(:,1,1))
Output(find(Sat==at(k,i)),find(Sar==ar(j,i)))=afr(k,j,i)
end
end
end
afr(:,:,i) is linked to the i_th column of ar and at. I need to create the a matrix of the following size [prod(size(at)),prod(size(ar))] where the elements of afr are sorted according to ar along the column and to at along the row. Here the result with the aforementioned data:
Ris=[0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0;
0 17 0 3 0 0 0 0 0;
0 0 0 0 0 0 0 4 1;
0 0 0 0 14 0 2 0 0;
4 3208 0 29 0 0 0 0 0;
0 0 0 0 0 0 0 1 0;
0 0 0 0 3 0 2 0 0;
6 127 0 12 0 0 0 0 0];
how can I make it faster?
Thanks
2 个评论
Geoff Hayes
2014-4-27
Hi pietro,
Why does the code need to be faster as it runs pretty quick as is. Are you anticipating larger matrices? Note that you could put the find(Sar==ar(j,i)) outside of the k (second inner) loop since ar does not depend on k,just i and j.
Geoff
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!