필터 지우기
필터 지우기

How to speed up my code?

조회 수: 1 (최근 30일)
George Bashkatov
George Bashkatov 2022년 2월 20일
댓글: George Bashkatov 2022년 2월 22일
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

채택된 답변

Akira Agata
Akira Agata 2022년 2월 20일
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
Walter Roberson
Walter Roberson 2022년 2월 22일
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 2022년 2월 22일
Thank you a lot

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by