Cut out all of a square array except for a specified NxN section in the middle.

조회 수: 1 (최근 30일)
Will Hertz
Will Hertz 2020년 11월 18일
편집: Bruno Luong 2020년 11월 18일
How can I take the following square array (or any other square array ebtered by the user) and take the center NxN square?
For example:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
is entered along with specifications for the middle 2x2, so it becomes
6 7
10 11
Here is my code thus far:
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
As you can see, I have done all the data validation. I am stuck on the actual performance of the task.
Thank you in advance!

답변 (2개)

Timo Dietz
Timo Dietz 2020년 11월 18일
Try this:
rowOffset = (rowdim-m)/2;
columnOffset = (columndim-m)/2;
centerMatrix = x(rowOffset+1:end-rowOffset, columnOffset+1:end-columnOffset);
  댓글 수: 1
Timo Dietz
Timo Dietz 2020년 11월 18일
Since rowOffset always equals cloumnOffset, you can certainly use one variable, only.

댓글을 달려면 로그인하십시오.


Bruno Luong
Bruno Luong 2020년 11월 18일
편집: Bruno Luong 2020년 11월 18일
This works on nd-array, any size (>=m) in all dimension:
i = num2cell(floor((size(x)-m)/2)+(1:m)',2)
FinalMatrix = x(i{:})

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by