Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circularly shifting a vector

I have a vector which is like

x = [20 11 12 13 14 15 16 17 18 19]

I would like to shift the vector values as given

if (i = 1)
X = [11 12 13 14 15 16 17 18 19 20]

if (i = 2)
X = [12 13 14 15 16 17 18 19 20 11]

if (i = 3)
X = [13 14 15 16 17 18 19 20 11 12] 

At present I am using a for loop to do this, but it takes a lot of time

x  = [20 11 12 13 14 15 16 17 18 19];
in = x;
C1 = x;

for lt = 1:1:length(in)
    C1 = x ; 

    if (lt > 1) 
        for tt = 1:1:lt-1
            swap = C1(1);

            for pt = 1:1:length(in)-1
                C1(pt) = C1(pt+1);    
            end   

            C1(length(in)) = swap;
        end
    end    

    disp(C1);
end

Could some one please suggest me a faster algorithm?

like image 436
Bow Avatar asked Dec 29 '25 05:12

Bow


2 Answers

Let s denote the number of positions you want to shift. You can use circshift:

x_shifted = circshift(x, [1 -s]);

The second argument is [1 -s] because you want to shift s positions to the left in the second dimension (columns).

You can also do it manually with mod:

x_shifted = x(mod((1:numel(x))+s-1, numel(x))+1);
like image 158
Luis Mendo Avatar answered Dec 31 '25 17:12

Luis Mendo


circshift is the way to go but you could also do it with pretty simple indexing:

x_shifted = x([(i+1):end , 1:(i-1)])

This however assumes that 1 < i && i < length(x).

like image 42
Dan Avatar answered Dec 31 '25 18:12

Dan