假设A是5x5的零矩阵:
>> B = ones(2)
B =
1 1
1 1
B是一个小的矩阵(2x2):
C1, C2, C3, ..., C16
现在,我正在寻找代表C1 =
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
C2 =
0 0 0 0 0
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
0 0 0 0 0
C3 =
0 0 0 0 0
0 0 0 0 0
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
这是:
C16
...最后C16 =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 1 1
0 0 0 1 1
等于:
{{1}}
正如你所看到的,它就像较小的矩阵(B)在较大的一个(A)内移动。
非常感谢,
答案 0 :(得分:5)
您可以使用circshift(...)
在shift the values about the Matrix的相应行和列上实现您想要的效果。您提到的示例是“移动矩阵元素”中显示的示例。页面的一部分,带有4x4矩阵。
以示例为例
A = [1 1 0 0; 1 1 0 0; 0 0 0 0; 0 0 0 0]
A =
1 1 0 0
1 1 0 0
0 0 0 0
0 0 0 0
Y = circshift(A,[1 1])
Y =
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0
在Mathworks网站上,有一个内置函数,它看起来就像你想要的那样。在5x5矩阵上显示16个组合的确切代码可以保持小矩阵在大矩阵中移动的错觉
编辑:所以它现在有一个5x5x16矩阵,输出名为C
A=zeros(5,5);
A(1:2,1:2)=1
c=1;C=zeros(5,5,16);
for i=0:3
for j=0:3
C(:,:,c)=circshift(A,[i j])
c=c+1;
end
end
产生输出(NOTE输出未编辑)
A =
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
ans =
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
ans =
0 1 1 0 0
0 1 1 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
ans =
0 0 1 1 0
0 0 1 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
ans =
0 0 0 1 1
0 0 0 1 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
ans =
0 0 0 0 0
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
0 0 0 0 0
ans =
0 0 0 0 0
0 1 1 0 0
0 1 1 0 0
0 0 0 0 0
0 0 0 0 0
ans =
0 0 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 0
0 0 0 0 0
ans =
0 0 0 0 0
0 0 0 1 1
0 0 0 1 1
0 0 0 0 0
0 0 0 0 0
ans =
0 0 0 0 0
0 0 0 0 0
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
ans =
0 0 0 0 0
0 0 0 0 0
0 1 1 0 0
0 1 1 0 0
0 0 0 0 0
ans =
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 0
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 1 1
0 0 0 1 1
0 0 0 0 0
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 1 0 0 0
1 1 0 0 0
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 1 0 0
0 1 1 0 0
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 1 1 0
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 1 1
0 0 0 1 1
答案 1 :(得分:3)
使用bsxfun
-
%// Get sizes and form size parameters for creating output
[mA,nA] = size(A);
[mB,nB] = size(B);
mC = mA - mB + 1;
nC = nA - nB + 1;
%// Get linear indices
stage1 = bsxfun(@plus,[1:mB]',[0:nB-1]*mA); %//'
stage2 = bsxfun(@plus,[1:mC]',[0:nC-1]*mA)-1; %//'
idx = bsxfun(@plus,stage1(:),stage2(:).' + [0:mC*nC-1]*mA*nA); %//'
%// Replicate A to setup output; index into it with idx & replace B
C = repmat(A,1,1,mC*nC);
C(idx) = repmat(B(:),1,mC*nC)
示例运行 -
A =
1 1 8 4
9 8 8 2
7 9 5 1
7 9 2 9
B =
3 5
3 6
3 1
C(:,:,1) =
3 5 8 4
3 6 8 2
3 1 5 1
7 9 2 9
C(:,:,2) =
1 1 8 4
3 5 8 2
3 6 5 1
3 1 2 9
C(:,:,3) =
1 3 5 4
9 3 6 2
7 3 1 1
7 9 2 9
....
C(:,:,6) =
1 1 8 4
9 8 3 5
7 9 3 6
7 9 3 1
答案 2 :(得分:2)
我认为这样做的好方法
A = zeros(5);
B = ones(2);
C = cell(size(A,1)-size(B,1) + 1, size(A,2)-size(B,2) + 1);
for i = 1:size(A,1)-size(B,1) + 1
for j = 1:size(A,2)-size(B,2) + 1
C{i, j} = A;
C{i, j}(i:i+size(B,1) - 1, j:j+size(B,2) - 1) = B;
% Additional code here
end
end
C = C(:);
% Additional code here