how can i make the centre elements of a matrix to become zeros
    10 ビュー (過去 30 日間)
  
       古いコメントを表示
    
I am writting a function that takes an n-by-m matrix and and an odd interger k as input arguments. both n and m are odd numbers as well and are all bigger than k. the function should return the input argument with its center k-by-k matrix zeroed out. this is how my function looks like currently and it is not producing the correct output. please help. 
function A= cancel_middle(A,k)
for ii=1:k
   for jj=1:k
        A(end/2+1/2:end/2+1/2)=0;
   end
end
end
0 件のコメント
採用された回答
  Jan
      
      
 2018 年 12 月 9 日
        
      編集済み: Jan
      
      
 2018 年 12 月 11 日
  
      The body of the loop does not use the indices ii and jj at all, so the code does not depend on k in any way.
Call size at first to determine the dimension of A. Then find out, which indices will be affected, if you need k rows and columns at the center. You do not need loops to assign the zeros, but the approach A(c1:c2, r1:r2) = 0 is sufficient.
0 件のコメント
その他の回答 (2 件)
  Elijah Smith
      
 2018 年 12 月 9 日
        
      編集済み: Elijah Smith
      
 2018 年 12 月 9 日
  
      this is what I came up with:
function A = cancel_middle(A, k)
    [n, m] = size(A);
    array2add = zeros(k);
    if n > k && m > k
        A((floor(n/2) - floor(k/2) + 1):(floor(n/2) - floor(k/2) + k), (floor(m/2) - floor(k/2) + 1):(floor(m/2) - floor(k/2) + k)) = array2add;
    end
end
it just replace the middle k-by-k matrix with zeros and if the rows/cols are add it defaults to the top left.
  Image Analyst
      
      
 2018 年 12 月 9 日
        
      編集済み: Image Analyst
      
      
 2018 年 12 月 9 日
  
      Try getting rid of the for loops and just finding the middle element and setting it to zero
middleLinearIndex = ceil(numel(A) / 2);
A(middleLinearIndex) = 0;
0 件のコメント
参考
カテゴリ
				Help Center および File Exchange で Dates and Time についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



