Vectorize for loop: corr2(A(:,:,i),B(:,:,i))
3 ビュー (過去 30 日間)
古いコメントを表示
Hi, I am trying to accelerate a function and am unable to perform this myself, so I am hoping for your help.
I have a set of 10.000 small images (64x64), and I need to calculate the correlation coefficient for each of these images. This is the code:
clear all
clc
close all
A=rand(64,64,10000);
B=rand(64,64,10000);
corr_result=zeros(1,1,size(A,3));
tic
for i=1:size(A,3)
corr_result(i)=corr2(A(:,:,i),B(:,:,i));
end
toc
I found this, it results in a 64x64x1 matrix, but I need a 1x1x10000 matrix.... Thanks for your input!!
5 件のコメント
Ameer Hamza
2020 年 12 月 3 日
I think this is already as efficient as it can get in MATLAB. After JIT optimizations, for-loops are not as slow as one might think.
採用された回答
Bruno Luong
2020 年 12 月 3 日
編集済み: Bruno Luong
2020 年 12 月 3 日
If you have R2020b, you mght try to vectorize with pagemtimes function (or use mtimesx from File exchange)
meanA = mean(A,[1 2]);
meanB = mean(B,[1 2]);
Ac = A-meanA;
Bc = B-meanB;
Ac = reshape(Ac,[],1,size(A,3));
Bc = reshape(Bc,[],1,size(B,3));
% psfun = @(a,b) sum(a.*b,1);
psfun = @(a,b) pagemtimes(a,'transpose',b,'none');
C = psfun(Ac,Bc)./sqrt(psfun(Ac,Ac).*psfun(Bc,Bc))
3 件のコメント
Bruno Luong
2020 年 12 月 3 日
Divide the calculation into a chunks that do not exeed your PC ram, eg 8e4 images.
その他の回答 (0 件)
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!