【问题标题】:How can I take three consecutive terms of an array every nth terms?如何每隔 n 项取一个数组的三个连续项?
【发布时间】:2017-04-02 14:15:23
【问题描述】:

谁能指导我如何使用 MATLAB 代码从一维向量中每隔 n 个元素选择数组的多个连续项(例如 3 个)?

例如,如果我的数组是 array = [1 2 3 4 5 6 7 8 9 10 11 12]; 我想连续三个词跳四个之后,所以解决方案是 array_solution = [1 2 3 8 9 10];

非常感谢。

【问题讨论】:

  • 这不是我想要的,我编辑了这个问题,所以现在我认为最好解释一下我的意思
  • 知道了。看看我的回答

标签: arrays matlab indexing


【解决方案1】:

使用bsxfun添加两个索引向量(列和行):

x = [1 2 3 4 5 6 7 8 9 10 11 12];
len = length(x); % total array length
c = 3; % number of consecutive elements
n = 4; % every nth element
idxs = bsxfun(@plus,(1:c)',0:(c+n):len);
y = x(idxs(:))

    y =

     [1     2     3     8     9    10]

【讨论】:

  • 是的,非常感谢,这正是我所需要的 :)
【解决方案2】:

如果您出于某种原因不想使用bsxfun(或一般的函数调用),这里有另一种方法可以在每个n 元素中获取c 连续元素。

x = 1:12;
c = 3;
n = 4;
% One of the two ranges in the indexing expression must be transposed
% so that MATLAB will apply vector expansion
y = x( (0:n+c:end-c) + (1:c)')

    y = 
        1    2    3
        8    9   10

如果您希望结果是 1xm 向量,也可以使用下一个 sn-p。

idxs = (0:n+c:end-c) + (1:c)';
y = x(idxs(:))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多