Insert smaller matrix into larger matrix with an equal number of columns.

1 Ansicht (letzte 30 Tage)
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.

Akzeptierte Antwort

Jan
Jan am 22 Jan. 2019
Bearbeitet: Jan am 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 Kommentare
Donald Christie
Donald Christie am 22 Jan. 2019
Well that simple error makes me feel like a right plum.
Cheers for the help.
Jan
Jan am 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"?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by