Using accumarray to sum all values associated with a given node

Given a graph with the following edges
edges = [1 2; 2 3; 3 1; 2 4; 4 5; 4 1];
I have some data associated with each edge
data=[0.276
0.679
0.655
0.162
0.118
0.333];
For a given node, I want to sum the data values corresponding to all edges it's connected to. How do I do this? accumarray looks promising, but this gives six nonzero values, when there should just be 5 (and I don't know how to distinguish which one corresponds to which node).
sum_data = accumarray(edges,data);

 採用された回答

Matt J
Matt J 2024 年 1 月 22 日
編集済み: Matt J 2024 年 1 月 22 日
One way:
edges = [1 2; 2 3; 3 1; 2 4; 4 5; 4 1];
data=[0.276
0.679
0.655
0.162
0.118
0.333];
G=graph(edges(:,1), edges(:,2), data);
out=sum(adjacency(G,'weighted'),2)
out =
(1,1) 1.2640 (2,1) 1.1170 (3,1) 1.3340 (4,1) 0.6130 (5,1) 0.1180

4 件のコメント

L'O.G.
L'O.G. 2024 年 1 月 22 日
Thanks, is there a way to do it without computing the graph explicitly?
Matt J
Matt J 2024 年 1 月 22 日
編集済み: Matt J 2024 年 1 月 22 日
What do you mean by "compute the graph explicitly"? There are no computations involved in the creation of the graph object G. It just stores the table of edges and weights that you already have.
L'O.G.
L'O.G. 2024 年 1 月 22 日
Ah ok, I was just wondering if I could've used accumarray after all. Thank you!
Matt J
Matt J 2024 年 1 月 22 日
編集済み: Matt J 2024 年 1 月 22 日
You could (see my other answer), but I'm pretty sure that's what the adjacency() command is already doing internally.

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

その他の回答 (1 件)

Matt J
Matt J 2024 年 1 月 22 日
編集済み: Matt J 2024 年 1 月 22 日
edges = [1 2; 2 3; 3 1; 2 4; 4 5; 4 1];
data=[0.276
0.679
0.655
0.162
0.118
0.333];
m=max(edges(:));
A=accumarray(edges,data,[m,m],[],0,1);
out=sum(A+A.',2) %assume it's a non-directed graph
out =
(1,1) 1.2640 (2,1) 1.1170 (3,1) 1.3340 (4,1) 0.6130 (5,1) 0.1180

カテゴリ

ヘルプ センター および File ExchangeSpline Postprocessing についてさらに検索

製品

リリース

R2021b

質問済み:

2024 年 1 月 22 日

編集済み:

2024 年 1 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by