lnk
lnk

Reputation: 603

Multiply matrix to vector

I've got matrix A(n,m) and I want multiply it to vector b(n), so that the result B[n,m]=A[n,m]*b[n]. It is possible to do it by creating a new matrix C=b*ones(1,m) and then use dot multiplication: B=A.*C, but it is waste of memory (size of A is 5000*1000). It is possible to use loops. Maybe there are more elegant way to do it?

Upvotes: 2

Views: 145

Answers (2)

sebas
sebas

Reputation: 879

Your first idea was good. Generate C with the elements of b, and then multiply B=A.*C . But you are right, it will take a lot of memory. If you do something similar but creating the matrix C being only the diagonal of a sparse matrix, it will do the same but saving a lot of memory.

B = spdiags(b,0,n,n)*A;

Your matrix is now in the left side of A because you are scaling the rows, but puting the new diagonal matrix in the left you will do the same for the columns.

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

Use bsxfun, which is just for that:

B = bsxfun(@times, A, b(:));

Upvotes: 5

Related Questions