代码之家  ›  专栏  ›  技术社区  ›  smci

获取给定索引前后(窗口+/-1)的向量索引

  •  0
  • smci  · 技术社区  · 7 年前

    给定的最佳Matlab/倍频程习惯用法是什么 idx 索引向量,用于获取 idx +/-1 ?

    我有一个n x 7的数据矩阵,第3列是一个整数标签,我对查看它上不连续的邻域很感兴趣。 因此,我得到了相应的指数:

    idx = find(diff(data(:,3)) > 0)
    
    5297
    6275
    6832
    ...
    20187
    

    然后,如果我想查看列上的邻域+/-1(例如,(mx2)矩阵上的邻域+/-1 [idx-1; idx+1] ),我需要形成 idx-1, idx+1 按顺序连接或重新连接。 我找到了一些笨拙的方法,正确的方法是什么? (我尝试了所有 octave chapter on Rearranging Matrices )

    % WAY 1: this works, but is ugly - a needless O(n) sort
    sort([idx-1; idx+1])
    
    % horzcat,vertcat,vec only stack it vertically
    horzcat([idx-1; idx+1])
    horzcat([idx-1; idx+1]')
    
    % WAY 2?
    %One of vec([idx-1; idx+1]) or vec([idx-1; idx+1]') should work? but doesn't, they always stack columnwise
    horzcat([idx-1; idx+1]')
    
    ans =
    Columns 1 through ...
    5297    6275    6832 ...  20187    5299    6277    6834 ... 20189
    
    % TRY 3...
    reshape([idx-1; idx+1], [36,1]) doesn't work either
    

    您可能认为只有两种方法可以取消堆叠2xm矩阵,但是。。。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Wolfie Radu Stefan    7 年前

    您可以通过隐式单例扩展(R2016b或更新的MATLAB,固有于倍频程)来实现这一点

    idx = [2, 6, 9]; % some vector of integers
    % Use reshape with [] to tell MATLAB "however many rows it takes"
    neighbours = reshape( idx + [-1;1], [], 1 );
    
    >> neighbours = [1; 3; 6; 8; 8; 10];
    

    如果你不知道 idx 是行或列,可以通过使用

    neighbours = reshape( idx(:)' + [-1,1], [], 1)
    

    如果不想使用隐式扩展(并再次处理行或列 idx公司 ),可以像这样使用重塑

    neighbours = reshape( [idx(:)-1, idx(:)+1]', [], 1 )
    

    注意:您可能还希望将整个过程包装在对的调用中 unique . 在我的示例中,您可以得到索引 8 有两次,我不确定这在你的情况下是可取的还是不可取的。

    然而 唯一的 执行排序(除非使用 'stable' 标记,但这可能会使其变得更慢),因此如果要删除重复项,最好使用原始方法:

    % Remove duplicates and sort the result using unique 
    neighbours = unique( [idx-1, idx+1] );
    
        2
  •  0
  •   smci    7 年前

    嗯,我终于找到了这个倍频程矩阵操作:

    vec([idx-1, idx+1]')
    ans =
    
    5297
    5299
    6275
    6277
    6832
    6834
    ...
    20187
    20189
    

    将Wolfie的解决方案改编为最短的纯倍频程代码:

    [idx-1, idx+1]' (:)  
    ( idx(:)' + [-1; 1] )(:) 
    

    idx = ( find(diff(data(:,3)) > 0 )' + [-1; 1] )(:) 用作一个衬里

    ... 和 [idx , data(idx,3)] 并排显示索引和数据