# How to speed up my code?

1 view (last 30 days)
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

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);
George Bashkatov on 22 Feb 2022
Thank you a lot

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2020a

### Community Treasure Hunt

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

Start Hunting!

Translated by