I am working with matrix operations in MATLAB, and I would have the following problem. I have matrix containing zero elements:


and another matrix with significantly smaller dimension containing value 6:


I define some coordinates in matrix a: a(45,50). I also consider this point as center of matrix b(2,2). I need to copy to matrix a the elements from matrix b, whose center is defined by b(2,2). I just know that it can be done manually by defining coordinates in matrix a. Please, is there any way, or inbuilt MATLAB function how to do it automatically? I am just MATLAB beginner.

  • $\begingroup$ Are there additional details you would share to help improve answers? $\endgroup$ Commented Sep 3, 2016 at 17:09

2 Answers 2


Just for the display, the following works as long as you are doing right: you do not try to copy b values outside of a, because you did not specify what should be done when you are at a(100,100). My choice is a circular shift, with a toroidal topology.

% a = zeros(100); aX = 45 ; aY = 50; 
a = zeros(12); aCenter = [4 6];
b = 6 * ones(3); bCenter = ceil(size(b)/2);


Basically, this creates a 2D logical indexing of b of the same size as a, with ones in the top left:


then circshift moves this pattern by the vector aCenter-bCenter:


Finally, the elements of a with the above logical indexing are affected with the values in b.


You can easily do this by using the sparse function, which allows you to construct matrices by supplying a list of non-zero indices. Here is a short example. Note that I have formatted the local blocks to show the matrix structure, even though they are represented as vectors.

% Define i indices in local coordinates
i = [-1,  0,  1,...
     -1   0   1,...
     -1   0   1];
% Define j indices in local coordinates
j = [ 1,  1,  1,...
      0   0   0,...
     -1  -1  -1];
% Construct 100 x 100 sparse matrix by using offsets
a = sparse(i + 45, j + 50, 6, 100, 100);
% Show subset of matrix
full(a(43:47, 48:52))
  • $\begingroup$ Thank you very much for response, but, unfortunately, I would need to make it without using of sparse matrix. Please, is there any way how to make it with using common matrix format (zeros (100,100))? Thank you very much. $\endgroup$
    – jendula11
    Commented Aug 26, 2016 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.