Assigning a vector to multiple rows of a matrix
Show older comments
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
Accepted Answer
More Answers (2)
Jos (10584)
on 16 May 2014
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 Comments
Omar Peza
on 22 Nov 2019
Thanks!
Chenglei QIAO
on 28 May 2020
Thanks! but I'm wondering why in this case, the for loop is even faster than the built-in repmat function?
Yao Li
on 16 May 2014
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,:)]
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!