# Defining a function that detects square matrices

Define a function g, which receives a list and returns True if that list represents a square array, and False otherwise.

I only can use Table, Map, and Apply.

Examples:

g[{{1,2,3},{4,5,6},{7,8,9}}] deverá retornar True
g[{{1,2,3},{4},{7,8}}] deverá retornar False
g[{{1,2,3},{4,5,6}}] deverá retornar False
g[{{1,2},1+x}] deverá retornar False


This is my code:

gl =
Function[w,
Apply[
And,
Table[If[w[[i]] == Length[w], True, False], {i, 1, Length[w]}]]]


or

g =
Function[w,
Apply[And, Map[Function[x, If[x == Length[x], True, False]], w]]]

• 1) Statements like If[test, True, False] is always equal to simply test: Remember that If checks whether test == True. Nov 27, 2016 at 11:44
• @MariusLadegårdMeyer Strictly speaking, your statement is not true. If test does not evaluate to True or False, then If remains unevaluated and is not equivalent to test (they are different expressions). Nov 27, 2016 at 11:48
• 2) When your test is w[[i]] == Length[w] or x == Length[x], you are asking whether the i'th row of w (generally a vector if w is a list of Depth 2 like in all the examples) is equal to the number of rows in w. What you want is to check that the number of columns is equal to the number of rows, right? Then Length[w[[i]]] will give you the number of columns in row i. Nov 27, 2016 at 11:49
• @LeonidShifrin, of course, I forgot about that in this context sigh. Thanks for pointing it out :) Nov 27, 2016 at 11:52
• Nov 27, 2016 at 14:22

The only problem is that for a $n \times 1$ matrix, Dimensions may b a singleton so

g = If[MatrixQ[#] && Length[Dimensions[#]] == 2 &&
Dimensions[#][[1]] == Dimensions[#][[2]], True, False] &


Now if

l = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
g[l]


gives true and false for the other cases

• The OP states "I only can use Table, Map, Apply..." though. Nov 27, 2016 at 15:02
• True but the answer seems to satisfy Paulo Rodrigues Nov 27, 2016 at 16:28
• g[{{1, 2}, {3, {4, 5, 6, 7, 8}}}] returns True which seems wrong. Nov 27, 2016 at 20:27
• Simon Woods, your Matrix is ambiguous and for Mathematica Dimensions[{{1, 2}, {3, {4, 5, 6, 7, 8}}}] si {2, 2}. Nov 27, 2016 at 22:12
• But {{1, 2}, {3, {4, 5, 6, 7, 8}}} // MatrixQ returns False, as does ArrayQ. So at least as far as Mathematica is concerned, Dimensions` are not the only thing to take into account. Nov 28, 2016 at 1:57