循环移位矢量 [英] Circularly shifting a vector
本文介绍了循环移位矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个载体,其像
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]
在present我使用的是为
循环来做到这一点,但它需要大量的时间
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?
推荐答案
让取值
表示要移仓的数量。您可以使用 circshift
:
Let s
denote the number of positions you want to shift. You can use circshift
:
x_shifted = circshift(x, [1 -s]);
第二个参数是 [1 -s]
,因为你要取值
位置转移到的左的在第二的维(列)。
The second argument is [1 -s]
because you want to shift s
positions to the left in the second dimension (columns).
您也可以手动将其与 MOD
:
You can also do it manually with mod
:
x_shifted = x(mod((1:numel(x))+s-1, numel(x))+1);
这篇关于循环移位矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文