MATLAB: Circshift matrix by different amount without for loop

circshiftMATLAB

Hello everyone. I have this 3 dimensional matrix called spectrums and I want to shift the 3rd dimension by different amounts given by vector shifts. Is there a way to do this without using a for loop? something like
shifted_spectrums=arrayfun(@(k) circshift(spectrums(:,:,k),shifts(2:end),2),spectrums);
but a solution that actualy works 😛
PS: 3rd dimension of spectrums has 22 elements and shifts has 23 elements, that's why the 2:end.

Best Answer

I've just got it working. A reshape is needed so the output has wanted size (sz1=1024, sz2=8192).
shifted_spectrums=reshape(cell2mat(arrayfun(@(k) circshift(spectrum(:,:,k)...
,shifts(k,1),2),1:Nfiles,'uni',0)),sz1/2,sz2,Nfiles);
This version is faster than the for loop
for i=2:Nfiles
shifted_spectrums(:,:,i)=circshift(spectrums(:,:,i),shifts(i-1,1),2);
end
Although not by much (16%, spectrums is a 512x8192x22 matrix)