How to speed up my code?

1 view (last 30 days)
George Bashkatov
George Bashkatov on 20 Feb 2022
Commented: George Bashkatov on 22 Feb 2022
I have a code with a lot of cycles and matrix multiplication. Input data: vector M of matrices 2x2, n2 - length of vector M (number of matrices 2x2). k - current matrix. My matrix do cyclic multiplication. It goes from the k-th element to the first, after that to last and after that to the (k+1)th.
E.g. n2=6, k=2: M2*M1*M2*M3*M4*M5*M6*M5*M4*M3
I was trying to turn vector M to gpuArray, also I was trying to turn cycles, that started from "for i=1:n2" to parfor but it didn't help. So, it's the problem with number of cycles? Can you give me some advices how to solve these problems and how avoid problems like these in future?
for i=1:n2
K(:,:,i)=M(:,:,i);
end
for i=1:n2 %return the original matrix for the new cycle
J(:,:,i)=K(:,:,i);
end
%cycle from k-th element to the beginning
if k == 1
else
for i=k-1:-1:1
M(:,:,i)=M(:,:,i+1)*M(:,:,i);
K(:,:,i)=M(:,:,i);
end
%return the original matrix, change the first element
for i=1:n2
M(:,:,i)=J(:,:,i);
end
M(:,:,1)=K(:,:,1);
end
%loop from beginning to end
for i=1:n2-1
M(:,:,i+1)=M(:,:,i)*M(:,:,i+1);
K(:,:,i+1)=M(:,:,i+1);
end
%return the original matrix, change the "last" element
for i=1:n2
M(:,:,i)=J(:,:,i);
end
M(:,:,n2)=K(:,:,n2);
if n2 == k
M(:,:,1)=K(:,:,n2-1);
else
%loop from end to (k+1)th element
for i=n2:-1:k+2
M(:,:,i-1)=M(:,:,i)*M(:,:,i-1);
end
end

Accepted Answer

Akira Agata
Akira Agata on 20 Feb 2022
Avoiding for-loop will enhance computational efficiency.
For example, the first for-loop:
for i=1:n2
K(:,:,i)=M(:,:,i);
end
should be as follows:
K(:,:,1:n2)=M(:,:,1:n2);
  3 Comments
Walter Roberson
Walter Roberson on 22 Feb 2022
No, for two different reasons:
  1. the * operator is not vectorizable. The closest you can get to that https://www.mathworks.com/help/matlab/ref/pagemtimes.html
  2. With you looping like that, you are creating a cummulative matrix product, M(:,:,end), M(:,:,end)*M(:,:,end-1), M(:,:,end)*M(:,:,end-1)*M(:,:,end-2), and so on. So the results for any given iteration depend upon the results for the previous iterations. That is not something that can be vectorized... not even with pagemtimes .
If you were using the .* operator instead of the * operator then with a permute(), reshape(), flipud(), cumprod(), flipud(), reshape(), permute() you could get the answer without a loop. But with the * operator, you need a loop.
George Bashkatov
George Bashkatov on 22 Feb 2022
Thank you a lot

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!