Assigning a vector to multiple rows of a matrix

조회 수: 106 (최근 30일)
Niko
Niko 2014년 5월 15일
댓글: Chenglei QIAO 2020년 5월 28일
Hi all,
This is actually something I've been wondering for a while... Say I have a 1-by-4 vector A and a 5-by-4 matrix B. Now I want to assign the vector A to certain rows of B, but unfortunately you can't do something like
B([1,3,5],:)=A
since the dimensions will mismatch. What I ended up doing is
B([1,3,5],:)=repmat(A,3,1)
which works but seems really ugly (and probably slow as well since I used repmat). Is there a better way to do this?
Thanks!
Niko

채택된 답변

W. Owen Brimijoin
W. Owen Brimijoin 2014년 5월 16일
You could try using indices instead of subscripts:
%pick the rows in B you want to your A values to go into:
r = [1 3 5];
%and the corresponding columns:
c = [1 2 3];
%now get your indices:
idx = sub2ind(size(B),r,c);
%and use these indices as follows:
B(idx) = A(c);
This assumes that you want your columns filled in the order that they are found in A, but you could just as easily make a different index into A to pick particular values from that vector. This works as long as you ask for the same number of values from A as you have slots in B, if you follow me.
B(idx) = A([2 3 4]);
  댓글 수: 1
Dang Manh Truong
Dang Manh Truong 2016년 12월 11일
편집: Dang Manh Truong 2016년 12월 11일
I'm sorry but it did not work :(

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

추가 답변 (2개)

Jos (10584)
Jos (10584) 2014년 5월 16일
Indeed, it looks a little ugly. However, using repmat is not that slow. Another, little uglier, but slightly faster and more straightforward solution is using a for-loop
A = 1:5
B = zeros(5,5) ;
for k = [1 3 5], B(k,:) = A ; end
  댓글 수: 2
Omar Peza
Omar Peza 2019년 11월 22일
Thanks!
Chenglei QIAO
Chenglei QIAO 2020년 5월 28일
Thanks! but I'm wondering why in this case, the for loop is even faster than the built-in repmat function?

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


Yao Li
Yao Li 2014년 5월 16일
b=ones(5,4);
a=[1;2;3;4];
If you wanna assign a to the 3rd row of b,
b=[b(1:2,:);a';b(4:5,:)]

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by