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?
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:
However, approach 4 would be to look into the documentation for matrices, as a likely place for such constructions, and there you will find
NullMatright after theIdentityMathere:The library function happens to be more efficient. Here we call each function a million times and compare the runtime in milliseconds:
The performance differs even much more dramatically for larger dimensions:
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.