Vectorize for loop: corr2(A(:,:,i),B(:,:,i))

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 commentaires

Deepak Gupta
Deepak Gupta le 3 Déc 2020
Modifié(e) : Deepak Gupta le 3 Déc 2020
I ran this code and got a matrix of size 64x64x10000 matrix. Don't know what's the problem.
Ameer Hamza
Ameer Hamza le 3 Déc 2020
but I need a 1x1x10000 matrix
Can you explain how? Shouldn't it be 64x64x10000?
William Thielicke
William Thielicke le 3 Déc 2020
Modifié(e) : William Thielicke le 3 Déc 2020
Sorry guys, the code was updated shortly after I posted this question. When you run it like it is posted above, you get a 1x1x10000 matrix. So for each of the 10000 image pairs, I get one correlation coefficient - which is what I want.
Ameer Hamza
Ameer Hamza le 3 Déc 2020
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.
William Thielicke
William Thielicke le 3 Déc 2020
But Matlab is only using 50% of my CPU during this operation. I bet there is a faster way...

Connectez-vous pour commenter.

 Réponse acceptée

Bruno Luong
Bruno Luong le 3 Déc 2020
Modifié(e) : Bruno Luong le 3 Déc 2020

0 votes

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 commentaires

William Thielicke
William Thielicke le 3 Déc 2020
Thank you, your solution is 3 - 4 times faster, and gives the identical result:
William Thielicke
William Thielicke le 3 Déc 2020
... but beware when you hit the limit of your RAM.... then it suddenly becomes 7 times slower. Is there a way to predict which method is faster BEFORE doing the calculation? I guess it has something to do with the memory used by the variables and the available RAM.
Bruno Luong
Bruno Luong le 3 Déc 2020
Divide the calculation into a chunks that do not exeed your PC ram, eg 8e4 images.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by