How to Copy and Paste a Small Matrix into a Bigger Matrix Without for-Loop

For example, we have a small matrix

B = [5 2, 
     3 4]

and the bigger one

A = [1 0 0 0 0
     0 1 0 0 0
     0 0 1 0 0
     0 0 0 1 0
     0 0 0 0 1]

Now I want paste B into A so that A looks like

A = [1 0 0 0 0
     0 1 0 0 0
     0 0 1 0 0
     0 0 0 5 2
     0 0 0 3 4]

That means the values of A of the bottom right has been replaced. I would like to do this without using a for-loop. How is that possible?

PS:

  1. A is always an eye(n) matrix (n is a constant).
  2. B is a square matrix and has a variable size but is always less or equal to A

1 Answer

Find the relevant row and column subscripts of A and put B there.

A(end-size(B,1)+1:end, end-size(B,2)+1:end)=B

It works even if B is not a square matrix.

Your Answer

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

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest