# Error in Assignment

I want to create a matrix with each element updated as per the formula, whose inputs are dependent on the location of element in the matrix.

Zphat[t] = ConstantArray[0, {4, 2, 2}]


The assignment is done using this:

For[i = 1, i < 5, i++, For [j = 1, j < 3, j++ , For [n = 1, n < 3, n++, For[k = 1, k < 5, k++, Zphat[t][[1, j, n]] = Zphat[t][[i, j, n] + D[zdot[t][i,j], {q[t][[1, k]], 1}]*smat[t][[k, n]]]]]]


I have checked the matrix dimensions used. zdot and smat are the appropriate matrices derived earlier.

Error message: Set::setps: Zphat[t] in the part assignment is not a symbol.

• To be able to correct the error we need the whole code: who are zdot[], q[t], smat[t] ? – TeM Jun 27 '19 at 20:51
• Unrelated to your question, but as you will often hear here, using For is going to make your life much, much worse. In fact using procedural code in Mathematica will just generally be slow and more work than using the built in functional constructs. There's a very good Q/A here on good alternatives to For. – b3m2a1 Jun 28 '19 at 0:26

## 2 Answers

Zphat[t] = ConstantArray[0, {4, 2, 2}] means "whenever you see the expression Zphat[t], replace it with the result of evaluating the ConstantArray expression."

There's a special case of Part that allows you to modify part of an expression that's bound to a symbol. But Zphat[t] isn't a symbol: it's a more complicated expression, so that special case doesn't apply.

Generally, the easy way to construct a matrix according to a formula is to use Table rather than constructing it and modifying it.

To answer the question in the comments:

x = {1, 2};


binds the expression {1,2} to x. This means "when you evaluate x, rewrite it as {1,2}". However, = (Set) holds its left hand side unevaluated, and does a special thing when it's a [[]] (Part) expression:

x[] = 3;
x
(* {1, 3} *)


Note that it can modify any expression this way, not just a List:

x = y + z;
x[] = 3;
x
(* 3 + y *)

• Could you explain what an expression that's bound to a symbol mean? – anhnha Oct 26 '19 at 0:26

I was able to use Table to solve the expression. I have performed the calculation in 2 steps.

Zphat[t] =  Table[D[zdot[t][[i, j]], {q[t][[1, k]], 1}]*smat[t][[k, n ]], {i, 4} , {j, 2}, {n, 2}, {k, 4}]


and for summation over the variable k

Zphatfinal[t] = Table[Sum[Zphat[t][i, j, n, k], {k, 2}], {i, 4} , {j, 2}, {n, 2}]


Also, refer to this before using For - Why should I avoid the For loop in Mathematica?