我正在寻找一种使用索引值进行循环移动的方法。
我知道我可以使用circshift命令移动所有值,见下面的
a=[1:9]
b=circshift(a,[0,1])
但是如何将每个第3个值更改为1?
例:
注意:变量a
可以是任意长度
a=[1,2,30,4,5,60,7,8,90] %note variable `a` could be any length
我试图让b
成为
b=[1,30,2,4,60,5,7,90,8] % so the values in the index 3,6 and 9 are shifted over 1.
答案 0 :(得分:3)
您无法使用circshift
的标准用法执行此操作。还有其他几种方法可以解决这个问题。这里只是几个。
mod
创建索引值您可以使用mod
从位置3:3:end
的索引值中减去1,并将1
添加到位置2:3:end
的索引值。
b = a((1:numel(a)) + mod(1:numel(a), 3) - 1);
<强>解释强>
在mod 3
上调用1:numel(a)
会产生以下序列
mod(1:numel(a), 3)
% 1 2 0 1 2 0 1 2 0
如果我们从这个序列中减去1,我们得到&#34; shift&#34;对于给定的指数
mod(1:numel(a), 3) - 1
% 0 1 -1 0 1 -1 0 1 -1
然后我们可以将此班次添加到原始索引
(1:numel(a)) + mod(1:numel(a), 3) - 1
% 1 3 2 4 6 5 7 9 8
然后将a
中的值分配给b
中的这些位置。
b = a((1:numel(a)) + mod(1:numel(a), 3) - 1);
% 1 30 2 4 60 5 7 90 8
reshape
。另一个选择是将您的数据重塑为3 x N
数组并翻转第2行和第3行,然后重新塑造回原始大小。 此选项仅在numel(a)
可被3 整除时才有效。
tmp = reshape(a, 3, []);
% Grab the 2nd and 3rd rows in reverse order to flip them
b = reshape(tmp([1 3 2],:), size(a));