Reputation: 263
I have a sparse matrix which only has elements in three diagonals. E.g.
I also have a column vector where I wish to multiply every element in each row of the sparse matrix by the corresponding element in each row of the column vector. Is there an efficient way to do this in MATLAB? If the sparse matrix is called A
and the column vector B
, I've only tried
A.*repmat(B,[1,9])
which is obviously inefficient.
Upvotes: 1
Views: 345
Reputation: 124563
Here's one way:
C = bsxfun(@times, A, B)
According to docs, the resulting matrix C
is sparse:
Binary operators yield sparse results if both operands are sparse, and full results if both are full. For mixed operands, the result is full unless the operation preserves sparsity. If S is sparse and F is full, then S+F, S*F, and F\S are full, while S.*F and S&F are sparse. In some cases, the result might be sparse even though the matrix has few zero elements.
Upvotes: 4