# Array multiply each column of sparse matrix by a column vector

## Alec Jacobson

## August 16, 2011

I was using essentially a dense matrix operation to multiply each column in a sparse matrix by a constant column vector:
```
S = sprandn(1000,1000,0.01);
% random sparse matrix
S = sprandn(1000,1000,0.01);
% random sparse matrix
S = sprandn(1000,5000,0.01);
% random column vector of same size
v = rand(size(S,1),1);
% old way: repeat column vector for each column in sparse matrix
old = S .* repmat(v,1,size(S,2));
```

It's much faster to use the builtin bsxfun function with the binary operation times:
```
% new way: use bsxfun with binary times function
new = bsxfun(@times,S,v);
```

**Update:** There is a much better way, by utilizing sparse matrix-matrix multiplication:
```
new = diag(sparse(v))*S;
```

Source