circshift columns and rows with different shifting units

how to vectorise this code to reduce the runtime:
clear;
clc;
profile on
tic
A=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]);
end
toc

 Accepted Answer

Jan
Jan on 2 May 2017
Edited: Jan on 2 May 2017

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:

A = magic(5);
x = [5 2 1 4 3];
tic
I = zeros(size(A));
R = size(A, 1);
for u = 1:length(x)
    % I(:,u) = circshift(A(:, u), [x(u) 0]);
    % Inlined CIRCSHIFT:
    index   = mod(-x(u):R-1-x(u), R) + 1;
    I(:, u) = A(index, u);
end
toc

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)]:

I = zeros(size(A));
R = size(A, 1);
x = mod(x - 1, R) + 1;  % X -> [1, R], omit this line if not required
for u = 1:length(x)
    index   = [R-x(u)+1:R, 1:R-x(u)];
    I(:, u) = A(index, u);
end

This runs in 0.0138 seconds.

2 Comments

thanks Jan.... Can u suggest the same code to run in the opposite direction?? ie.. the code below is for the rows to shift from left to right and columns from upwards to downwards...how it works for rows from right to left and columns from downwards to upwards????
tic A=magic(5);
x=[5 1 3 2 4];
I = zeros(size(A));
I1 = zeros(size(A));
R = size(A, 1);
% x = mod(x - 1, R) + 1; % X -> [1, R], omit this line if not required
for u = 1:length(x)
index = [R-x(u)+1:R, 1:R-x(u)];
I(:, u) = A(index, u);
I1(u,:) = A(u,index);
end
toc
All you have to change is the index:
index = [1+x(u):R, 1:x(u)];

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 2 May 2017

Commented:

Jan
on 2 May 2017

Community Treasure Hunt

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

Start Hunting!