1
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ To be able to correct the error we need the whole code: who are zdot[], q[t], smat[t] ? $\endgroup$ – TeM Jun 27 at 20:51
  • $\begingroup$ 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. $\endgroup$ – b3m2a1 Jun 28 at 0:26
1
$\begingroup$

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.

$\endgroup$
1
$\begingroup$

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?

$\endgroup$

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.