【问题标题】:Is it possible to convert multiple local regions in a matrix to a new matrix?是否可以将矩阵中的多个局部区域转换为新矩阵?
【发布时间】:2016-04-02 14:49:29
【问题描述】:

例如,如果我有一个10×10 矩阵,并且我在该矩阵中有一个n 坐标列表,我想在每个坐标周围取一个3×3 区域,将其调整为长度@ 987654324@向量,然后将所有向量堆叠成一个9×n矩阵。我知道我可以编写一个 for 循环来执行此操作,但这似乎很糟糕,尽管我可能最终会这样做。

【问题讨论】:

  • 第一个想法:您可以编写一个运行n 次的循环,而不是运行10*10 次。坐标的数量肯定会少于10*10(或矩阵中的元素数量)。这将节省一些计算时间,因为您几乎可以对所有其他任务进行矢量化。在伪代码中类似于for i=1:n ; extract 3x3 region surrounding coordinate *i* ; concatenate matrix

标签: matlab matrix


【解决方案1】:

我不确定这是否比 for 循环更高效,但您可以对索引值进行一些计算。

data = magic(5);

%//     17    24     1     8    15
%//     23     5     7    14    16
%//      4     6    13    20    22
%//     10    12    19    21     3
%//     11    18    25     2     9

%// The coordinates you want to sample at (row, col)
coords = [2 3; 3 2; 2 4];

%// Determine the row and column offsets to apply for a 3x3 block
[rowOffset, colOffset] = ndgrid(-1:1,-1:1);

%// Compute the rows and columns included in each block centered t each point
rows = bsxfun(@plus, coords(:,1).', rowOffset(:));
cols = bsxfun(@plus, coords(:,2).', colOffset(:));

%// Convert to absolute linear index and sample data at these regions
newdata = data(sub2ind(size(data), rows, cols));

%//   24    23     1
%//    5     4     7
%//    6    10    13
%//    1     5     8
%//    7     6    14
%//   13    12    20
%//    8     7    15
%//   14    13    16
%//   20    19    22

话虽如此,根据您想对这些组中的每一个做什么,您可以潜在地使用卷积或其他东西来完成同样的事情。

【讨论】:

    【解决方案2】:

    假设坐标已经是索引形式,你可以这样使用:

    m = 10;
    A = rand(m);
    cc = [23; 47; 64];
    ind = bsxfun(@plus, [(-1:1) - m, (-1:1), (-1:1) + m], cc);
    newVals = A(ind);
    

    或者先将坐标转换成索引形式:

    c1 = [3 3; 7 5; 4 7];
    cc = sub2ind(size(A), c1(:,1), c1(:,2));
    

    当然,这不会检查坐标是否在矩阵的边缘,如果有任何坐标会抛出错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多