# Create a matrix without definition of dimensions

is it possible to define a matrix without giving its dimensions in Mathematica,

e.g.

First line:

mattest[[1,2]] = 1;


Second line:

mattest[[4,2]] = 2;


....

Error

Set::noval: Symbol mattest in part assignment does not have an immediate value.


Such definition works in Matlab:

>> mattest(1,2)=1;
mattest(4,2)=2;
mattest

mattest =

0     1
0     0
0     0
0     2

• A little clunky but if you make an empty list, you could use append or prepend to add the elements? You would need to write so it adds the empty lists before - m={} adding your first line would need { {}, {1} } – Teabelly Jun 2 at 13:22

mattest = SparseArray@{{1, 2} -> 1, {4, 2} -> 2}

MatrixForm@mattest


If you just hate SparseArray without any reasonable reason, here's another possibility:

tomatrix[a_] :=
Replace[DownValues@a, (_[a[i__]] :> v_) :> {i} -> v, {1}] // SparseArray // Normal

mattest[1, 2] = 1;
mattest[4, 2] = 2;

normalmat = tomatrix@mattest
(* {{0, 1}, {0, 0}, {0, 0}, {0, 2}} *)


Notice in this case the generated matrix isn't stored in mattest.

• Sparse matrix is not wished in this case, can we have other simple commands to define such matrix? – ABCDEMMM Jun 1 at 11:39
• @ABCDEMMM Why is SparseArray not wished? It's simple enough in my view. You just don't like {} and ->? – xzczd Jun 1 at 11:43
• @a In the question you've clearly claimed that we should not give the dimensions of the matrix beforehand, while your ConstantArray method does. Still, you don't show a plausible reason for your dislike of SparseArray. – xzczd Jun 1 at 11:53
• @a Sparse matrix is undoubtedly a matrix, its usage is just the same as the normal matrix AFAIK. Or you happen to run into any case that SparseArray doesn't work well? If so, please show an example. – xzczd Jun 1 at 11:59