How to construct the zero matrix in GAP

152 Views Asked by At

How do I initialise a zero matrix in GAP in a reasonable way?

What I tried.

Approach 1. I'm aware that I can create the matrix by initialising an empty list, and going through a double for-loop. The problem I have with this approach is that it is uncomfortably cumbersome for something this basic. I'm sure that there must be a better way than this.

Approach 2. It would seem that there's a function ZeroMatrix(). I don't think it does what I want. It's mentioned in the manual here, but I cannot parse what it says.

Approach 3. A more elaborate approach I tried is the following.

> M := ListWithIdenticalEntries(3, ListWithIdenticalEntries(3, 0));
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

The problem is that the behaviour of this object is rather strange. Consider the following:

> M[1][1];
0
> M[1][1] := 1;
1
> M;
[ [ 1, 0, 0 ], [ 1, 0, 0 ], [ 1, 0, 0 ] ]

Why exactly does this happen?

1

There are 1 best solutions below

0
On BEST ANSWER

First off, approach 3 happens because the rows are identical so change in one happens in others. See the GAP manual here for an explanation.

Approach 2 tries to use a specialised function from the Gauss package, which seem to require as an argument a data structure defined by the Homalg package - so it wouldn't work.

There is nothing fundamentally wrong with approach 1. You can write own function (see e.g. https://carpentries-incubator.github.io/gap-lesson/03-func/index.html) and then call it when you need.

Just to advertise some compact way of writing such a function, consider this code:

gap> zeromat := {m,n} -> List([1..m], i -> List([1..n], j -> 0));
function( m, n ) ... end
gap> zeromat(3,3);
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

However, approach 4 would be to look into the documentation for matrices, as a likely place for such constructions, and there you will find NullMat right after the IdentityMat here:

gap> NullMat(3,3);
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

The library function happens to be more efficient. Here we call each function a million times and compare the runtime in milliseconds:

gap> for i in [1..1000000] do zeromat(3,3);od;time;
2154
gap> for i in [1..1000000] do NullMat(3,3);od;time;
836

The performance differs even much more dramatically for larger dimensions:

gap> for i in [1..100000] do zeromat(100,100);od;time;
45519
gap> for i in [1..100000] do NullMat(100,100);od;time;
1603

If you will look at its code using PageSource(NullMat); you will see that instead of assembling each row separately, it first creates a row of zeroes, and then copies it the required number of times.