2
$\begingroup$

Best to give an example. Let us consider the function AdjacencyMatrix. When we pass, say a matrix to it, we get:

test = {{1,1,1},{1,2,2},{3,3,3}};
AdjacencyMatrix[%]

AdjacencyMatrix::graph: A graph object is expected at position 1 in AdjacencyMatrix[{{1,1,1},{1,2,2},{3,3,3}}].

AdjacencyMatrix[{{1, 1, 1}, {1, 2, 2}, {3, 3, 3}}]

Is there a way of modifying AdjacencyMatrix so that if the argument isn't a graph object it would simply return the argument itself?

$\endgroup$
1
  • $\begingroup$ You want AdjacencyMatrix to return the argument itself only when it is a matrix, or whenever it is not a graph? $\endgroup$ Commented Jul 12, 2019 at 16:50

2 Answers 2

6
$\begingroup$

You can use Check in a user defined function:

adjacencyMatrix[g_] := Check[AdjacencyMatrix[g], g]

Then:

adjacencyMatrix[Graph[{1->2,2->3,3->4}]] //Normal
adjacencyMatrix[{1->2, 2->3, 3->4}] //Normal
adjacencyMatrix[{{1,2},{3,4}}]

{{0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, {0, 0, 0, 0}}

{{0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, {0, 0, 0, 0}}

AdjacencyMatrix::graph: A graph object is expected at position 1 in AdjacencyMatrix[{{1,2},{3,4}}].

{{1, 2}, {3, 4}}

$\endgroup$
1
  • 1
    $\begingroup$ This is much better than my approach. Note: OP may want to suppress the error message here: Quiet[Check[...], {AdjacencyMatrix::graph}]. $\endgroup$ Commented Jul 13, 2019 at 1:09
4
$\begingroup$

Bad answer:

Unprotect[AdjacencyMatrix];
AdjacencyMatrix[mat_List] := mat
Protect[AdjacencyMatrix];

Good answer:

adjacencyMatrix[graph_Graph] := AdjacencyMatrix[graph]
adjacencyMatrix[mat_List] := mat
$\endgroup$
2
  • $\begingroup$ For the good answer, maybe remove the pattern head List on the second line, as this is the behavior requested for anything that's not a Graph. $\endgroup$
    – Roman
    Commented Jul 12, 2019 at 16:46
  • $\begingroup$ @Roman good point. Let me ask OP to be sure. (If they only want the identity for matrices, then it is safer to leave List in). $\endgroup$ Commented Jul 12, 2019 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.