How to generate a sparse matrix for a given array?

1 回表示 (過去 30 日間)
Benson Gou
Benson Gou 2021 年 5 月 24 日
コメント済み: Benson Gou 2021 年 5 月 25 日
Dear All,
I want to generate a sparse matrix B for a given array A. A contains two columns of indecis. For example,
A = [1 3;
1 4;
2 3;
2 5;
3 5;
4 5]
The sparse matrix B should be as follows:
B = [ 2 0 -1 -1 0;
0 2 -1 0 -1;
-1 -1 2 0 0;
-1 0 0 2 -1;
0 -1 -1 -1 3]
The characteristics of B:
  1. Sum of each row is zero.
  2. If we consider matrix A gives the information of edges of a graph, B(i,i) = sum of number of edges, B(i,j) = -1 if there is an edge between i and j.
Thanks a lot.
Benson

採用された回答

Matt J
Matt J 2021 年 5 月 25 日
編集済み: Matt J 2021 年 5 月 25 日
B=laplacian( graph(A(:,1),A(:,2)) );
  5 件のコメント
Benson Gou
Benson Gou 2021 年 5 月 25 日
yes, it works well. Thanks a lot.
Benson
Matt J
Matt J 2021 年 5 月 25 日
You're welcome, but please Accept-click the answer that you deem best resolves your question.

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

その他の回答 (1 件)

the cyclist
the cyclist 2021 年 5 月 24 日
Here is one way:
A = [1 3;
1 4;
2 3;
2 5;
3 5;
4 5];
d = max(A(:));
B = sparse(A(:,1),A(:,2),-1,d,d) + sparse(A(:,2),A(:,1),-1,d,d);
for ii = 1:d
B(ii,ii) = -sum(B(ii,:));
end
disp(B)
(1,1) 2 (3,1) -1 (4,1) -1 (2,2) 2 (3,2) -1 (5,2) -1 (1,3) -1 (2,3) -1 (3,3) 3 (5,3) -1 (1,4) -1 (4,4) 2 (5,4) -1 (2,5) -1 (3,5) -1 (4,5) -1 (5,5) 3
  7 件のコメント
the cyclist
the cyclist 2021 年 5 月 25 日
I assume that doing what @Matt J suggested in his answer:
A=unique(sort(A,2),'rows')
is what you would need to do here as well.
If you posted a small example that exhibits the problem, it would help. But I'm guessing you have your answer.
Benson Gou
Benson Gou 2021 年 5 月 25 日
Hi, the Cyclist,
Thanks a lot for your great help. You have a good day!
Benson

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

カテゴリ

Help Center および File ExchangeAudio and Video Data についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by