ArrayDepth and Dimensions count square brackets as a dimension
Something relatively simple:
myArrayDepth[arr_] := If[ArrayQ[arr], ArrayDepth[arr], 0]
Test:
ArrayDepth[f[f[a, b], f[c, d]]]
2
myArrayDepth[f[f[a, b], f[c, d]]]
0
Alternatively, use TensorRank[]
:
TensorRank[{{1, 3}, {2, 4}}]
2
TensorRank[SparseArray[{1, 1} -> 1, {2, 2}]]
2
which remains unevaluated if given something that isn't a List[]
or a SparseArray[]
:
TensorRank[f[f[a, b], f[c, d]]]
TensorRank[f[f[a, b], f[c, d]]]
and throws a warning if not passed a rectangular array:
TensorRank[{{1, 2}, {3}}]
>> TensorRank::rect: Nonrectangular array encountered.
1
There is an undocumented option AllowedHeads
that can be used for this purpose (so the usual warnings about undocumented features applies here):
ArrayDepth[f[f[a,b], f[c,d]], AllowedHeads->{List}]
ArrayDepth[f[f[a,b], f[c,d]], AllowedHeads->{f}]
0
2
You can use SetOptions
in an init.m
file to change the default:
SetOptions[ArrayDepth, AllowedHeads->{List}];
ArrayDepth[{{a,b}, {c,d}}]
ArrayDepth[f[f[a,b], f[c,d]]]
2
0
Note that you can also mix and match heads using this option, but note that the heads have to be the same at any particular level:
ArrayDepth[f[{a,b}, {c,d}], AllowedHeads->{List, f}]
ArrayDepth[f[{a,b}, f[c,d]], AllowedHeads->{List, f}]
2
1
In line with my answer from the linked question:
myArrayDepth[arr_] := ArrayDepth[{arr}] - 1
Just like J.M.'s answer:
ArrayDepth[f[f[a, b], f[c, d]]]
myArrayDepth[f[f[a, b], f[c, d]]]
2 0