An Anya
An Anya

Reputation: 11

How to zero out the centre k by k matrix in an input matrix with odd number of columns and rows

I am trying to solve this problem:

Write a function called cancel_middle that takes A, an n-by-m matrix, as an input where both n and m are odd numbers and k, a positive odd integer that is smaller than both m and n (the function does not have to check the input). The function returns the input matrix with its center k-by-k matrix zeroed out.

Check out the following run:

>> cancel_middle(ones(5),3)
ans =
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1

My code works only when k=3. How can I generalize it for all odd values of k? Here's what I have so far:

function test(n,m,k)
   A = ones(n,m);
   B = zeros(k);
   A((end+1)/2,(end+1)/2)=B((end+1)/2,(end+1)/2);

   A(((end+1)/2)-1,((end+1)/2)-1)= B(1,1);
   A(((end+1)/2)-1,((end+1)/2))= B(1,2);
   A(((end+1)/2)-1,((end+1)/2)+1)= B(1,3);

   A(((end+1)/2),((end+1)/2)-1)= B(2,1);
   A(((end+1)/2),((end+1)/2)+1)= B(2,3);

   A(((end+1)/2)+1,((end+1)/2)-1)= B(3,1);
   A(((end+1)/2)+1,((end+1)/2))= B(3,2);
   A((end+1)/2+1,(end+1)/2+1)=B(3,3)
end

Upvotes: 1

Views: 908

Answers (2)

Karan Mahajan
Karan Mahajan

Reputation: 3

function b = cancel_middle(a,k)
[n,m] = size(a);
start_row = (n-k)/2 + 1;
start_column = (m-k)/2 + 1;
end_row = (n-k)/2 + k;
end_column = (m-k)/2 + k;
a(start_row:end_row,start_column:end_column) = 0;
b = a;
end

I have made a function in an m file called cancel_middle and it basically converts the central k by k matrix as a zero matrix with the same dimensions i.e. k by k. the rest of the matrix remains the same. It is a general function and you'll need to give 2 inputs i.e the matrix you want to convert and the order of submatrix, which is k.

Upvotes: 0

Matthias W.
Matthias W.

Reputation: 1077

You can simplify your code. Please have a look at Matrix Indexing in MATLAB. "one or both of the row and column subscripts can be vectors", i.e. you can define a submatrix. Then you simply need to do the indexing correct: as you have odd numbers just subtract m-k and n-k and you have the number of elements left from your old matrix A. If you divide it by 2 you get the padding on the left/right, top/bottom. And another +1/-1 because of Matlab indexing.

% Generate test data
n = 13;
m = 11;
A = reshape( 1:m*n, n, m )
k = 3;

% Do the calculations
start_row = (n-k)/2 + 1
start_col = (m-k)/2 + 1
A( start_row:start_row+k-1, start_col:start_col+k-1 ) = zeros( k )

Upvotes: 1

Related Questions