TransWikia.com

Defining a function that detects square matrices

Mathematica Asked by Paulo Rodrigues on December 7, 2020

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]]]

One Answer

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

Correct answer by cyrille.piatecki on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP