Improving speed of for-loop
Show older comments
Hello,
I am trying to improve the speed of the following for loop in Matlab. As it is now is incredibly slow. Maybe vectorizing or execute in parallel?
The problem is that the solution of the componentwise matrixproduct A*B has to be saved in the matrix component k,l based on its rank in matrix RX & RY.
Thanks!
for j=1:n
for i=1:n
a=A(i,j);b=B(i,j);
k=RX(i,j);l=RY(i,j);
covXY(k,l)=covXY(k,l)+a*b;
EX(k)=EX(k)+a;
EY(l)=EY(l)+b;
end
end
4 Comments
Jan
on 9 Dec 2018
Please provide meaningful input data. Is RX and RY unique? How large are the inputs? It matters, if you call this millions of times for a small input or once for a huge input.
Image Analyst
on 9 Dec 2018
Edited: Image Analyst
on 9 Dec 2018
It does not look like that should be slow. What are the sizes of RX, RY, covXY, EX, and EY? Are covXY, EX, and EY already in existence with the full size before the loop starts?
meko94
on 9 Dec 2018
Jan
on 10 Dec 2018
Are RX and RY unique?
length(RX(:)) == length(unique(RX(:)))
Answers (1)
Jan
on 10 Dec 2018
nX = max(max(RX));
nY = max(max(RY));
EX = accumarray(RX(:), A(:), [], @sum);
EY = accumarray(RY(:), B(:), [], @sum);
index = sub2ind([nY, nY], RX(:), RY(:));
covXY = accumarray(index, A(:) .* B(:), [nX*nY, 1], @sum);
I'm not sure, if this is faster. We could check this if you provide some test data, e.g. created by rand or randi.
5 Comments
meko94
on 11 Dec 2018
Jan
on 11 Dec 2018
@meko94: I'd really want to help you and have some ideas. Unfortunately you do not provide meaningful inputs and do not answer my question for clarification. If RX and RY or the combination of both is unique, there is a much easier and faster solution. But all I know, is that you call the values "rank", whatever this means.
meko94
on 11 Dec 2018
I will take a look into the MAT file as soon as I have access to a machine running Matlab - this can take some days. A short meaningful example would be useful.
Are A and B, and/or RX and RY symmetric?
Did you profile my accumarray approach? Perhaps creating EX and EY is faster with accumarray, but covXY is faster in the loop, because it avoids the expensive calculation of A.*B, if the memory is the bottleneck.
Do you have a C-compiler or the parallel processing toolbox? How much RAM does your computer have?
meko94
on 13 Dec 2018
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!