WILLIAM HERTZ
WILLIAM HERTZ

Reputation: 31

How do you find an 'M' by 'M' submatrix in the center of an input 'N' by 'N' matrix? (In Matlab)

How do I write a function in Matlab to output the M x M submatrix at the center of an N x N input matrix? The function should have two input arguments—the N x N input matrix (2D array) and the size of the square submatrix, M, to be extracted from the input matrix. The sole output should be the M x M submatrix at the center of the input matrix. The function should use for loops to extract the submatrix and not use colon notation or any built-in functions for this part of the code. The function should work for any square input matrix where N ≥ 3. If N is even, M should be even. If N is odd, M should be odd.

Here is a picture of my flowchart so far.

Upvotes: 1

Views: 169

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4757

Using For-Loops and Offsetting Indexing

Preface:

Here I like to visualize this question as trimming the matrix. The amount to trim I denote in this example is Trim_Amount. The Trim_Amount dictates the size of the sub-matrix and the start point to begin reading/saving the sub-matrix.

Scanning/Saving Sub-Matrix

Since the trim amount is always taken from each side you can expect the sub-matrix to have dimensions in the form:

Sub-Matrix Width = M - (2 × Trim_Amount)

2 × Trim_Amount will always result in an even number therefore the following can be said:

if M is even → M - (Even Number) → Even Number
if M is odd → M - (Even Number) → Odd Number


Test Output Results:

Output Results I recommend going through the code to filter through any unexpected issues.

Full Script:

Dimension = 7;
Matrix = round(100*rand(Dimension));
Trim_Amount = 1;

[Sub_Matrix] = Grab_Sub_Matrix(Matrix,Trim_Amount);
Matrix
Sub_Matrix
    
%Function definition%
function [Sub_Matrix] = Grab_Sub_Matrix(Matrix,Trim_Amount) 

%Minimum of M must be 5 since N >= 3%
[M,~] = size(Matrix);


%Ensuring the trimming factor does not go over possible range%
Max_Trimming_Factor = M - 3;
if(Trim_Amount > Max_Trimming_Factor)
Trim_Amount = Max_Trimming_Factor;
end


%Fill in the boundaries%
Row_Start_Limit = Trim_Amount + 1;
Column_Start_Limit = Trim_Amount + 1;

%Creating sub-matrix based on amount of trimming%
Sub_Matrix = zeros(M-(2*Trim_Amount),M-(2*Trim_Amount));

for Row = 1: length(Sub_Matrix)
   for Column = 1: length(Sub_Matrix) 
    
%    fprintf("(%d,%d)\n",Row,Column);  
   Sub_Matrix(Row,Column) = Matrix(Row + Row_Start_Limit-1,Column + Column_Start_Limit-1);
    
   end
end

end

Ran using MATLAB R2019b

Upvotes: 1

Related Questions