Matias Nordin pointed on a recent thread that circshift can be very slow.
I recently came across this fact in a different application, in which I need to do circshifts
repeatedly on a modestly sized 1D array. So I did some tests, see code below.
Amazingly it seems that for a 1D array of size 100, Matlab's circshift is 50 times slower than simply using a loop. Even using Matlab's colon notation directly is slower than a loop.
For larger arrays the colon notation is the fastest method.
I have not tried shifts by more than 1 place though I expect it would be similar.
For 2D arrays the effect is still there, though less extreme.
For circshift the CPU time hardly depends on the array size, indicating a significant startup overhead as the Matlab code does some checks on the array.
On my Linux PC this startup time is about 0.2ms.
The message seems to be that you should never use circshift!
% CHECK SPEED OF CIRCSHIFT VS OTHER METHODS. PCM 23/6/09
clear
n=100;nloop=10000;
x=linspace(1,1,n);
u=sin(pi*x);
% CIRCSHIFT  VERY SLOW
t=cputime;
for j=1:nloop
uc=circshift(u,[0,1]);
end
time_circshift=cputimet
% LOOP  MUCH FASTER  FASTEST IF n < 250
t=cputime;
for j=1:nloop
for k=2:n; ul(k)=u(k1);end;ul(1)=u(n);
end
time_loop=cputimet
% MATRIX MULTIPLY
t=cputime;
shiftmat=diag(ones(n1,1),1);shiftmat(n,1)=1;
for j=1:nloop
um=u*shiftmat;
end
time_matrix=cputimet
% SPARSE MATRIX MULTIPLY  FASTEST IF 250 < n < 600
t=cputime;
shiftmatsparse=sparse(shiftmat);
for j=1:nloop
ums=u*shiftmatsparse;
end
time_sparse_matrix=cputimet
% MATLAB COLON NOTATION  FASTEST IF n > 600
t=cputime;
for j=1:nloop
us=[u(n) u(1:n1)];
end
time_colon=cputimet
checks=[norm(uluc),norm(ulum),norm(ulums),norm(ulus)]
