【问题标题】:Selecting elements from a large matrix using a sliding window使用滑动窗口从大矩阵中选择元素
【发布时间】:2019-02-09 00:35:03
【问题描述】:

我有一个 220*366 的矩阵,我想设置一个 3*3 的窗口来选择矩阵中的元素。 示例:

matrix = [1, 2, 3, 4, 5;
          6, 7, 8, 9, 10;
          11,12,13,14,15];
window = [1, 2, 3;
          6, 7, 8;
          11,12,13];

【问题讨论】:

    标签: matlab matrix indexing subset sliding-window


    【解决方案1】:

    如果您有图像处理工具箱,可以使用nlfilter

    function out = q52158450()
    % Create a matrix:
    Rm = 220; Cm = 366;
    matrix = randn(Rm,Cm);
    
    % Define the window and apply filter:
    Rw = 6; Rc = 6;
    windows = nlfilter(matrix, [Rw, Rc], @getwindow);
    
    % Select subset of outputs, removing zero-padded boundary elements:
    Bw = floor((Rw-1)/2); Bc = floor((Rc-1)/2); 
    out = windows(Bw:end-Bw, Bc:end-Bc); % < Output is a cell
    
    function out = getwindow(in)
    out = {in};
    

    否则可以用双循环来完成:

    function out = q52158450()
    % Create a matrix:
    Rm = 220; Cm = 366;
    matrix = randn(Rm,Cm);
    
    % Define the window and apply filter:
    Wr = 3; Wc = 3;
    Br = ceil(Wr/2); Bc = ceil(Wc/2);
    out = cell(Rm-Br, Cm-Bc);
    
    for indR = 1:Rm-Wr+1
      for indC = 1:Cm-Wc+1    
        out{indR, indC} = matrix(indR:indR + Wr - 1, indC:indC + Wc - 1);
      end
    end
    

    【讨论】:

    • @yyk 不客气!如果您发现此答案有帮助,请考虑 accepting it 以表明您的问题已解决。
    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多