multiplying each non zero element of a sparse matrix by a certain number

8 ビュー (過去 30 日間)
Mnr
Mnr 2015 年 11 月 25 日
コメント済み: Mnr 2015 年 11 月 28 日
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.

採用された回答

Star Strider
Star Strider 2015 年 11 月 25 日
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
  2 件のコメント
Mnr
Mnr 2015 年 11 月 25 日
Thank you!
Star Strider
Star Strider 2015 年 11 月 25 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (2 件)

James Tursa
James Tursa 2015 年 11 月 25 日
編集済み: James Tursa 2015 年 11 月 25 日
W = S;
G = logical(S);
W(G) = W(G) .* P(:);
Note: This preserves the sparse attribute of S. I.e., if S is sparse, then W will be sparse. If S is full, then W will be full.
  3 件のコメント
James Tursa
James Tursa 2015 年 11 月 27 日
Ah ... I didn't notice that you wanted the multiplication by rows, not columns. So some transposes will be required for this method. E.g.,
W = S';
G = logical(W);
W(G) = W(G) .* P(:);
W = W';
Mnr
Mnr 2015 年 11 月 28 日
I really appreciate it!

サインインしてコメントする。


Stalin Samuel
Stalin Samuel 2015 年 11 月 25 日
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] ;
[r c] = size(S);
W = zeros(r,c);
n = 1;
for r1 = 1:r
    for c1 = 1:c
        if S(r1,c1)~=0
            W(r1,c1) =  S(r1,c1)*P(n) ;
            n = n+1;
        end
    end
end

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by