2
$\begingroup$

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
$\endgroup$
1
  • $\begingroup$ 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} } $\endgroup$ – Teabelly Jun 2 at 13:22
8
$\begingroup$
mattest = SparseArray@{{1, 2} -> 1, {4, 2} -> 2}

MatrixForm@mattest 

Mathematica graphics

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.

$\endgroup$
4
  • $\begingroup$ Sparse matrix is not wished in this case, can we have other simple commands to define such matrix? $\endgroup$ – ABCDEMMM Jun 1 at 11:39
  • $\begingroup$ @ABCDEMMM Why is SparseArray not wished? It's simple enough in my view. You just don't like {} and ->? $\endgroup$ – xzczd Jun 1 at 11:43
  • 2
    $\begingroup$ @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. $\endgroup$ – xzczd Jun 1 at 11:53
  • 1
    $\begingroup$ @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. $\endgroup$ – xzczd Jun 1 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.