1
votes

I have a sparse matrix which only has elements in three diagonals. E.g.

enter image description here

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.

1
"each row of the column vector" is just a scalar. Is that what you are doing?Hennadii Madan
@HennadiiMadan yes, but not to worry, Amro's solution is just what I was looking for :)Mike Miller

1 Answers

4
votes

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.