八度:矩阵中的多个子矩阵

fbr*_*eto 4 matlab wolfram-mathematica matrix octave submatrix

我有一个大矩阵,我想从中收集一组子矩阵.如果我的矩阵是NxN并且子矩阵大小是MxM,我想收集I=(N - M + 1)^2子矩阵.换句话说,我希望原始矩阵中的每个元素都有一个MxM子矩阵,它可以位于这种矩阵的左上角.

这是我的代码:

for y = 1:I
    for x = 1:I
        index = (y - 1) * I + x;
        block_set(index) = big_mat(x:x+M-1, y:y+M-1)
    endfor
 endfor
Run Code Online (Sandbox Code Playgroud)

输出如果a)错误,并且b)暗示big_mat(x:x+M-1, y:y+M-1)表达式中的某些东西可以得到我想要的东西,而不需要两个for循环.任何帮助将非常感激

Jon*_*nas 5

您的代码中似乎有一些问题.如果我使用双循环,我就是这样做的:

M = someNumber;
N = size(big_mat,1); %# I assume big_mat is square here

%# you need different variables for maxCornerCoord and nSubMatrices (your I)
%# otherwise, you are going to index outside the image in the loops!
maxCornerCoord = N-M+1;
nSubMatrices = maxCornerCoord^2;

%# if you want a vector of submatrices, you have to use a cell array...
block_set = cell(nSubMatrices,1); 
%# ...or a M-by-M-by-nSubMatrices array...
block_set = zeros(M,M,nSubMatrices);
%# ...or a nSubMatrices-by-M^2 array
block_set = zeros(nSubMatrices,M^2);

for y = 1:maxCornerCoord
    for x = 1:maxCornerCoord
        index = (y - 1) * maxCornerCoord + x; 
        %# use this line if block_set is a cell array
        block_set{index} = big_mat(x:x+M-1, y:y+M-1);
        %# use this line if block_set is a M-by-M-by-nSubMatrices array
        block_set(:,:,index) = big_mat(x:x+M-1, y:y+M-1);
        %# use this line if block_set is a nSubMatrices-by-M^2 array
        block_set(index,:) = reshape(big_mat(x:x+M-1, y:y+M-1),1,M^2);
    endfor
 endfor
Run Code Online (Sandbox Code Playgroud)

编辑

我刚看到Octave 有im2col的实现.因此,您可以将双循环重写为

%# block_set is a M^2-by-nSubMatrices array
block_set = im2col(big_mat,[M,M],'sliding');

%# if you want, you can reshape the result to a M-by-M-by-nSubMatrices array
block_set = reshape(block_set,M,M,[]);
Run Code Online (Sandbox Code Playgroud)

这可能更快,并节省了大量的数字树.