Insert smaller matrix into larger matrix with an equal number of columns.
4 views (last 30 days)
Show older comments
Hey guys, I have two Matrices with the same number of columns but different number of rows, and I wish to insert Matrix A into Matrix B so in this example:
A = rand(25,50);
B = zeros(50,50);
[M N] = size(A);
I then want to insert A into B, but I want to be able to define where I set them. So in this case:
X = 10;
Y = 35;
As they have the same number of columns I attempted to simply insert a couple of ways:
B(X:Y,1:end) = A; % This gives a "Subscripted assignment dimension mismatch"
B(X:Y, 1:N) = A; % Same error as above
B(X:Y,1:end) = A(1:M,1:end); % again same error
The output of this would be a (50,50) Matrix (B), with rows X:Y of B being replaced Matrix A.
Maybe a for loop would work here? I'm not entirely sure where to proceed from this point. Any help would be greatly appreciated.
0 Comments
Accepted Answer
Jan
on 22 Jan 2019
Edited: Jan
on 22 Jan 2019
X = 10;
Y = 35;
The problem is that X:Y has 26 elements, not 25. Remember: If A has 1 row only, you will not use: 10:11 but 10:10 only (which is the same as 10, of course).
Use X:Y-1 instead, then all 3 commands will work, or more general: X:X+M-1. I'd prefer the simpler:
B(X:(X + M - 1), :) = A;
2 Comments
Jan
on 22 Jan 2019
@Donald: You can be sure, that I've recognized the error, because I'm used to do it by my own. I'm using the mentioned method to catch this mistake: "What are the indices for inserting 1 or 2 elements"?
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!