user9802913
user9802913

Reputation: 245

How to get an adjacency matrix with weights?

How to get an adjacency matrix with weights?

Suppose I have

s=[1 1 2 2 2 3 3 4 4 4 5 5 6 7];

t=[2 3 4 5 3 5 6 5 7 8 6 8 7 8];

w=[3 5 4 7 4 9 8 3 11 8 3 9 8 7];

G=digraph(s,t,w)

It should have been created with this

A = adjacency(G,'weighted')

but marks an error that says

Error using digraph/adjacency Too many input arguments.

When I type A = adjacency(G) set all costs as 1.

Why?

Upvotes: 0

Views: 278

Answers (1)

Matt
Matt

Reputation: 1362

adjacency only accepts 1 input argument, which is why you are receiving that error. The function is only designed to return values of 0 or 1.

You can get the weighted adjacency matrix from the following, taken from the MATLAB documentation for the adjacency function.

nn = numnodes(G);
[s,t] = findedge(G);
A = sparse(s,t,G.Edges.Weight,nn,nn)

Alternatively, you can construct the weighted adjacency matrix without using graph objects.

nn = max([s, t]);
A = zeros(nn);
for i = 1:length(s)
  A(s(i), t(i)) = w(i);
end

Upvotes: 1

Related Questions