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!