2
$\begingroup$

I have to multiply the matrices in the reverse order such as

f[4].f[3].f[2].f[1]

Have to be done by loops, because I have to multiply 10000 matrices all numerical values, for example the below code,

dx=10;
M[j_,kz_]={{2 Sin[j dx kz], 3 Cos[j dx kz]},{Cos[5 j dx kz], Sin[4 j dx kz]}}

For[kz=4, kz<1-1, --kz,
For[j=1, j<20+1, j++,
M[j,kz]];

Can't figure out here

]

I need to multiply M[j,4].M[j,3].M[j,2].M[j,1]

$\endgroup$
1
  • $\begingroup$ Do you want to loop over kz and j, or just j? $\endgroup$
    – Chris K
    Commented Apr 23, 2020 at 14:36

1 Answer 1

5
$\begingroup$

If loops have to be adopted, you need to introduce a symbol to temporarily store the value in each step.

The following example shows how things will work. Here I use f[] to replace your M[]. And, in your case, "y" needs to be initially set as a unit matrix.

Code:

y = 1;
For[j = 1, j < 6, j++, 
 For[kz = 1, kz < 5, kz++, {x = f[j, kz].y, y = x}]]
y

Result:

f[5, 4].f[5, 3].f[5, 2].f[5, 1].f[4, 4].f[4, 3].f[4, 2].f[4, 1].f[3, 
  4].f[3, 3].f[3, 2].f[3, 1].f[2, 4].f[2, 3].f[2, 2].f[2, 1].f[1, 
  4].f[1, 3].f[1, 2].f[1, 1].1

Besides, I wonder if there is a specific reason for you to use loops. If not, I would like to suggest to avoid it in Mathematica. Try the following code that provides the same result. It runs much quicker in Mathematica.

Dot @@ Flatten@Table[f[j, kz], {j, 5, 1, -1}, {kz, 4, 1, -1}]
$\endgroup$

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