2
$\begingroup$

I am constructing matrices whose elements are lists themselves (of varying length), and am (re)setting the entries of these matrices using among others the "All" command. It seems that in this context, Mathematica's commands are not well-defined: for a vector A,

A[[All]] = x

in general sets all entries of A equal to x, except when x is a vector of the same length as A, in which case it instead gets interpreted to mean A = x.

As a concrete example,

A={a,b};
A[[All]]={1,2,3};

yields A as

{{1,2,3},{1,2,3}}

while

B={a,b};
B[[All]]={1,2};

yields B as

{1,2}

I realize the general behavior can be reproduced in the special case by using Hold[] in the evaluation, as in e.g.

F={a,b};
F[[All]]=Hold[{1,2}];
F=ReleaseHold[F];

which yields F as

{{1,2},{1,2}}

but I find this rather clunky.

Has anybody encountered this or related issues before and come up with a more elegant alternative?

I would also welcome any explanation as to why this behavior may actually be considered desirable (as opposed to allowing for e.g. an "Every" option in addition to "All"), or comments as to why other constructions (e.g. functions) are the more appropriate tool in Mathematica in this context.

$\endgroup$
2
  • $\begingroup$ Unfortunately, Mathematica "matrices" are just lists of lists, and thus your choice of matrices with list elements is not a good fit. Perhaps another data structure is a better fit for you. Maybe use A[i,j] instead of A[[i,j]]. $\endgroup$
    – Somos
    Nov 16, 2020 at 2:03
  • $\begingroup$ Thanks! I agree that using a function data structure can avoid this issue. In my context a matrix felt more intuitive however. Ideally I would have some elegant way of fixing up Mathematica's issues here, because lists (as representing also e.g. sets) are more fundamental than tensor connotations.. $\endgroup$
    – Stijn
    Nov 16, 2020 at 12:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.