MATLAB: Multiplying each non zero element of a sparse matrix by a certain number

MATLABmatrix

Hello all,
I have a sparse matrix S with few non-zero elements in its row and columns. I have a vector P with the same number of elements as the total non-zero elements of S. I would like to multiply each non-zero element of S by a value in P. For example, let
S = [0 0 1 1;0 1 1 0;1 1 0 0; 1 0 0 1]
P = [0.7421 0.3751 1.9079 1.4141 1.4411 2.0796 2.4199 1.1002]
I would like to get
W = [0 0 0.7421 0.3751;0 1.9079 1.4141 0;1.4411 2.0796 0 0; 2.4199 0 0 1.1002]
Can somebody please help me with a fast way of doing this task? Thank you.

Best Answer

This works — and NO LOOPS:
S = [0 0 1 1;0 1 1 0;1 1 0 0; 1 0 0 1] ;
P = [0.7421 0.3751 1.9079 1.4141 1.4411 2.0796 2.4199 1.1002];
Snz = find(S == 1);
Wv = S(Snz).*P';
W = zeros(1,numel(S));
W(Snz) = Wv;
W = reshape(W, size(S))'
W =
0 0 0.7421 0.3751
0 1.9079 1.4141 0
1.4411 2.0796 0 0
2.4199 0 0 1.1002