How to add a row matrix to all other rows of a matrix?
6 views (last 30 days)
Show older comments
Daan Van Cauteren
on 25 Oct 2017
Edited: Fragrant Sun
on 24 Oct 2018
In order to get the right values in my final matrix, I have to add a single column matrix (with the same amount of rows) to a bigger matrix. It's important that both matrices can be declared and initialized before adding them together. Basically, I already did this while using a simple for loop, but it's very time consuming for MATLAB to do this operation for every column (20.000 to 900.000 columns). I was wondering if there was a simpler/faster way to become the same result as the code snippet:
for a = 1:size(VarLasten,2)
VarLasten(:,a) = VarLasten(:,a) + Perm;
end
With VarLasten = the final matrix where every initial row is added with the corresponding value of the row matrix Perm. VarLasten = (m x n) and Perm = (m x 1).
1 Comment
Accepted Answer
Jos (10584)
on 25 Oct 2017
Edited: Jos (10584)
on 25 Oct 2017
Why not use simple concatenation? First transpose the row-vector into a m-by-1 column vector, of course:
NewVarLasten = [VarLasten Perm(:)]
2 Comments
John
on 3 Jan 2018
NewVarLasten = [VarLasten Perm(:)] will be N+1 columns and not the question to add Perm to each column to have the matrix VarLasten size unchanged.
Jos (10584)
on 4 Jan 2018
You're right :)
bsxfun is Daan's friend!
res = bsxfun(@plus, NbyMmatrix, Nby1Vector)
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!