# How to generate a matrix (node, edges) out of a graph?

For simulations of electricity networks i need incidence matrices. Is there a function, which generates the related matrix with node and eges. For example, if a node is connected with a edge the value will be 1, otherwise the value will be 0. Thank you for responses!

``````  function init() {
var \$ = go.GraphObject.make;

myDiagram =
\$(go.Diagram, "myDiagramDiv",
{
initialContentAlignment: go.Spot.Center,
"undoManager.isEnabled": true,
"ModelChanged": function(e) {     // just for demonstration purposes,
if (e.isTransactionFinished) {  // show the model data in the page's TextArea
document.getElementById("mySavedModel").textContent =
writeIncidenceMatrix(e.model); //e.model.toJson();
}
}
});

function writeIncidenceMatrix(model) {
var arr = computeIncidenceMatrix(model);
var str = "";
for (var j = 0; j < arr.length; j++) {
var row = arr[j];
var s = "";
for (var i = 0; i < row.length; i++) {
var val = row[i];
if (val === undefined) s += "   ";
else if (val < 0) s += " " + val;
else s += "  " + val;
}
str += s + "\n";
}
return str;
}

function computeIncidenceMatrix(model) {
if (!(model instanceof go.GraphLinksModel)) throw new Error("needs to be a GraphLinksModel");

var arr = [];
var nodeIndex = new go.Map(Object, 'number');
var na = model.nodeDataArray;
for (var i = 0; i < na.length; i++) {
arr.push([]);
}

var la = model.linkDataArray;
for (i = 0; i < la.length; i++) {
var linkdata = la[i];
var fromdata = model.findNodeDataForKey(fromkey);
var todata = model.findNodeDataForKey(tokey);

if (fromdata !== null && todata !== null) {
var fromarr = arr[nodeIndex.getValue(fromdata)];
fromarr[i] = -1;
var toarr = arr[nodeIndex.getValue(todata)];
toarr[i] = (fromarr === toarr) ? 2 : 1;  //?? how to handle reflexive edges
}
}

return arr;
}

myDiagram.model = new go.GraphLinksModel(
[
{ key: "Alpha", color: "lightblue" },
{ key: "Beta", color: "orange" },
{ key: "Gamma", color: "lightgreen" },
{ key: "Delta", color: "pink" }
],
[
{ from: "Alpha", to: "Beta" },
{ from: "Alpha", to: "Gamma" },
{ from: "Beta", to: "Beta" },
{ from: "Gamma", to: "Delta" },
{ from: "Delta", to: "Alpha" }
]);
}
``````

This is the same model as used in the Minimal sample, Minimal GoJS Sample. For simplicity I did not bother copying the templates from there or from the Basic sample.

The incidence matrix is written out as:

`````` -1 -1        1
1     2
1    -1
1 -1
``````

Note the 2 there for the reflexive link from “Beta” to “Beta”. You’ll need to decide how to handle that. Might not be a problem in your app.

Oh, I forgot to fill in zeros as a default value. Sorry – you can do that if you care.

Also this code ignores partially connected or completely disconnected links.

Note also that this code does not handle hypergraphs, when you have label Nodes that belong to Links.