how to vectorise this code to reduce the runtime:
clear;clc;profile onticA=magic(5);x=[5 2 1 4 3];I=zeros(length(x));for u=1:length(x) I(:,u)=circshift(A(:,u),[x(u) 0]);endtoc
alternate method for circshiftcircshiftfaster versions of circshiftperformance
clear;clc;profile onticA=magic(5);x=[5 2 1 4 3];I=zeros(length(x));for u=1:length(x) I(:,u)=circshift(A(:,u),[x(u) 0]);endtoc
Best Answer
A vectorization would not be very efficient: Instead of creating the output directly, you'd have to create an index matrix in addition. Try to accelerate the code by inlining circshift:
If A is a 1000x1000 matrix, this takes 0.0276 seconds instead of 0.0812 seconds with circshift.
Now mod is the bottleneck. We can move it out of the loop, or even omit it, if all x are inside [1, size(A,1)]:
This runs in 0.0138 seconds.