如何在奇数行和列的输入矩阵中将中心k乘以k矩阵归零 [英] How to zero out the centre k by k matrix in an input matrix with odd number of columns and rows

查看:65
本文介绍了如何在奇数行和列的输入矩阵中将中心k乘以k矩阵归零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决此问题:

I am trying to solve this problem:

编写一个名为cancel_middle的函数,该函数取n乘以m 矩阵,作为输入,其中n和m均为奇数,k为正 小于m和n的奇数整数(该函数不必 检查输入).该函数返回输入矩阵及其中心k-k 矩阵清零.

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.

检查以下运行:

>> 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

我的代码仅在k=3时有效.如何对k的所有奇数值进行归纳?这是我到目前为止的内容:

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

推荐答案

您可以简化代码.请查看 MATLAB中的矩阵索引. 行和列下标中的一个或两个都可以是向量",即您可以定义一个子矩阵.然后,您只需要正确地建立索引即可:因为您有奇数,所以只需减去mk和nk,您就可以从旧矩阵A中减去剩余元素的数量.如果将其除以2,您将获得左侧/右侧的填充,顶部/底部.还有一个+ 1/-1,是因为Matlab建立了索引.

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 )

这篇关于如何在奇数行和列的输入矩阵中将中心k乘以k矩阵归零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆