2016-09-21 65 views
1

我想使用:运营商,但定期提取矢量元素。作为一个例子,说a={1,2,3, ..., 10},我想提取元素的步骤2,改变参考。然后我想获得MATLAB:定期提取元素

ref 1: 1 3 5 7 9 
ref 2: 2 4 6 8 10 
ref 3: 3 5 7 9 1 
... 

在MATLAB中是否存在一个关键字来强制它是周期性的?或者我必须首先将circshift应用于阵列,然后提取?

回答

4

您可以使用模运算构建索引:mod(...-1, numel(a))+1。需要那些-1+1,因此得到的索引是基于1的(而不是基于0的)。

a = [1 2 3 4 5 6 7 8 9 10]; % vector to be indexed 
ref = 3; % first value for index 
step = 2; % step for index 
ind = mod(ref+(0:step:numel(a)-1)-1,numel(a))+1; % build index 
result = a(ind); % apply index 
1

你可能产生两个索引集:id1 = 1:2:length(a);id2 = 2:2:length(a);。然后你可以在这些索引数组上使用circshift来获得所需的数组。

1

你说过一个矢量,所以我会假设你的意思是a = [1,2,3, ..., 10]。如果a是一个单元格,请在下面的代码中使用b = cell2mat(a)并用b替换a

我想你circshift是做到这一点的最好办法,但你可以很快

a = 1:10; 
acirc = cell2mat(arrayfun(@(n) circshift(a', [-n,0]), 0:length(a)-1, 'uni', 0))'; 
aout = acirc(:, 1:2:end) 

这使得a的从0转变矩阵做一个:9。然后它会每第二个元素下降。然后,如果你想要一个单元阵列

aout = num2cell(aout,2) 
1

第一连接两个范围[1:10]作为水平要被提取的索引:

IDX = [1:10 1:10] 

然后使用函数来提取n元件从begin与分离开始step

ref = @(begin,step, n) IDX(begin : step : begin+(n * step)-1); 

例如:

ref(1,2,5) 
ref(2,2,5) 
ref(3,2,5) 
ref(4,2,5)