在matlab中,去掉除中间指定的NxN部分以外的所有方形数组



如何获取以下方阵(或用户筛选的任何其他方阵(并获取中心NxN正方形?例如:

1    2    3    4
5    6    7    8
9    10   11   12
13   14   15   16

与中间2x2的规格一起输入,因此它成为

6    7
10   11

这是我迄今为止的代码:

function [FinalMatrix] = arraycenter(x, m)
% arraycenter takes a large square NxN matrix and trims away everything
% other than the center 'm'x'm' submatrix.
% x must be a square 2 dimension matrix that is at least 3x3
% m must be an integer less than or equal to N, and if N is even, m
% must be even, and vice versa
% Find dimensions of x and check to make sure it is a square, 2D matrix
columndim = size(x, 1);
rowdim = size(x, 2);
pagedim = size(x, 3);
if columndim < 2 || rowdim < 2 || pagedim ~= 1
error('Your first matrix entered was not two dimensional. Try again.')
end
if columndim ~= rowdim
error('Your first matrix was not a square. Try again.')
end
% Make sure m is the correct size
if m >= columndim || m >= rowdim
error('m is too large. Try again.')
end
% Make sure N and m match (N is odd, m is odd; N is even, m is even)
if rem(rowdim, 2) == 0 && rem(m, 2) == 1
error('N is even and m is odd. Try again.')
end
if rem(rowdim, 2) == 1 && rem(m, 2) == 0
error('N is odd and m is even. Try again.')
end
% Perform the operation to find the center matrix
end

正如你所看到的,我已经完成了所有的数据验证。我拘泥于任务的实际执行。提前谢谢!

下面的函数从另一个矩阵的中心裁剪出一个方形矩阵。它不控制代码中实现的偶数/奇数条件。如果不能根据x的尺寸和m的值创建相等的边距,则上边距和左边距将比右边距和下边距小一个元素。

function [y, sI, eI] = arraycenter(x, m)
% returns an m by m matrix from center of square matrix x
% startIndex and endIndex are index of first and last 
%   column (or row) if x that will be copied to y,
%   so that y = x(sI:eI, sI:eI)
% check if x is a square 2d matrix
sz = size(x);
if ~ismatrix(x) || sz(1)~=sz(2)
error('x must be a square 2D matrix');
end
% check id m is equal or less than d
d = sz(1);
if m>d
error('m must be equal or less than size(x, 1).');
end
sI = floor((d-m)/2)+1;
eI = sI+m-1;
y = x(sI:eI, sI:eI);
end

但如果你坚持通知来电者所有的利润将不相等,你也可以添加以下控件:

if mod((d-m), 2)
warning('y can not be exactly at the center of x.');
end

像一样使用

n = 5;
M = magic(n)
for i=1:n
fprintf('%dx%d:n', i, i);
disp(arraycenter(M, i));
end

M=

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  

1x1:

13  

2x2:

5     7  
6    13  

3x3:

5     7    14  
6    13    20  
12    19    21  

4x4:

17    24     1     8  
23     5     7    14  
4     6    13    20  
10    12    19    21  

5x5:

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  

最新更新