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

조회 수: 1 (최근 30일)
Donald Christie
Donald Christie 2019년 1월 22일
댓글: Jan 2019년 1월 22일
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.

채택된 답변

Jan
Jan 2019년 1월 22일
편집: Jan 2019년 1월 22일
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
Donald Christie
Donald Christie 2019년 1월 22일
Well that simple error makes me feel like a right plum.
Cheers for the help.
Jan
Jan 2019년 1월 22일
@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"?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by