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?
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With