How to create a matrix that has zero in middle?

function x=cancel_middle1(n,A)
x=n;
x(size(n)-A:end-1,size(n)-A:end-1)=0;
got answer here
cancel_middle1(ones(7),3)
ans =
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 0 0 0 1
1 1 1 0 0 0 1
1 1 1 0 0 0 1
1 1 1 1 1 1 1
and
cancel_middle1(ones(7),5)
ans =
1 1 1 1 1 1 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 1 1 1 1 1 1
I want input cancel_middle1(ones(7),3) to be
cancel_middle1(ones(7),3)
ans =
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 0 0 0 1 1
1 1 0 0 0 1 1
1 1 0 0 0 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
How can I fix my function?

 Accepted Answer

The line
x(size(n)-A:end-1,size(n)-A:end-1)=0;
is full of bugs.
First, what is the output of size(n)? It's guaranteed to be a vector with at least 2 elements (more for N-D arrays).
So size(n)-A is a vector with at least 2 elements.
Now what happens when you use a vector with the : operator? It's actually documented: If you specify nonscalar arrays, then MATLAB interprets j:i:k as j(1):i(1):k(1). So, you're always using the 1st index of the vector returned by size, which is the size of the first dimension.
The code you've written is equivalent to
x(size(n, 1)-A:end-1,size(n, 1)-A:end-1)=0;
% ^ ^
% | |
% --------------------------------- dimensions being indexed. Always 1
Notice the dimensions you index in size. Are they correct?
The second issue, of course, is that if the intent is for the zeros to be centered in the matrix, you ought to calculate the location of that centre, which you typically get by dividing the size by 2. So somewhere in the code there should be a division by 2,
As this looks like homework, I'm not giving the solution, but that should get you going.

More Answers (0)

Categories

Products

Tags

Community Treasure Hunt

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

Start Hunting!