How to add a matrix into a specific part of a matrix?

I have one 4x4 matrix and I'm trying to add a 2x2 matrix to the middle of the 4x4 matrix. I've tried a few commands, but have mainly been told that the dimensions don't agree. I appreciate any help.

2 Comments

Please post your code and a copy of the complete error message.
Matrix dimensions must agree.
Error in PS03_matrix_magic_olivo_heying (line 38) A(2,:) + M(1,:)

Sign in to comment.

 Accepted Answer

It is difficult to provide help without giving away the solution. I have a working solution. I would prefer to see your solution first, to determine what the problem is.

4 Comments

I've already tried: A = [A(1,:)+ E; A(2,:) + M(1,:); A(3,:) + M(2,:); A(4,:) + F]; Please excuse the E and F as those are just other variables I have to use this code. Also, M is the 2x2 I also tried: A = [A(1,:)+ E; A(2,:) + M; A(4,:) + F]; And was still given the same error.
Well, you’ve given it an honest effort, at least in my opinion, so I’ll give you my solution:
A = randi(9, 4)
B = randi([90 99],2)
A(2:3, 2:3) = A(2:3,2:3) + B
A =
6 3 2 6
7 6 9 2
6 5 1 9
9 3 6 3
B =
97 97
98 95
A =
6 3 2 6
7 103 106 2
6 103 96 9
9 3 6 3
NOTE — I use random integers, so you will not get the same result. However if I understand your Question correctly, your result should look like mine.
This only works on a range of contiguous indices. For a range specific indices defined by a range, use the sub2ind function. Explore that at your leisure.
Thank you! Now I'm just working on making the values I change it to remain permanent, but I'll try to do that on my own first.
As always, my pleasure!

Sign in to comment.

More Answers (1)

A = reshape(1:16, 4, 4); % Some test data
E = rand(2, 2);
A(2:3, 2:3) = A(2:3, 2:3) + E;
I have no idea, what F could be. It would be useful if you explain the details.
I hope this is not a homework. Otherwise my answer made it harder for you to deliver your own solution.

1 Comment

It is part of a homework. I just wanted to know where to start off really because our typical professor has been out and the TA hasn't been much help in teaching the material. I don't realy understand what you given me, but it at least ives me something to experiment with since i tried everything I knew.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!