# Returning the argument of a function if the argument is not of the right type

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[{{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?

• You want AdjacencyMatrix to return the argument itself only when it is a matrix, or whenever it is not a graph? – AccidentalFourierTransform Jul 12 at 16:50

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


{{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}}

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

• This is much better than my approach. Note: OP may want to suppress the error message here: Quiet[Check[...], {AdjacencyMatrix::graph}]. – AccidentalFourierTransform Jul 13 at 1:09

Unprotect[AdjacencyMatrix];

adjacencyMatrix[graph_Graph] := AdjacencyMatrix[graph]

• 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. – Roman Jul 12 at 16:46
• @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). – AccidentalFourierTransform Jul 12 at 16:49