1
$\begingroup$

I have the following code,

dx=0.02;
dz=0.05;
Ein[j_,kz_]=2(j dx+kz dz);

For[kz=1, kz<5+1, kz++,
For[j=-5, j<5+1, j++,
Ax[j, kz]= 4/5 (Ein[j+1, kz]-Ein[j, kz]);
];
Ein[j,kz]=Ax[j, kz]
]

Why it is not replacing the values of Ein[j, kz] with the Ax[j, kz], when running for the next loop kz > 1;

I mean how to replace Ein[j+1, kz] with Ax[j+1, kz] and Ein[j, kz] with Ax[j, kz]?

Then I need to recall the values of new Ein[j,1], Ein[j,4] etc... at different kz..

$\endgroup$
1
  • 1
    $\begingroup$ Why are you not directly assigning the values to Ein[j, kz], as in Ein[j, kz]=4/5(...)? Since the Ax[j, kz] only depend on the "current" and "future" Ein[j, kz], you'll never override any values of Ein[j, kz] too soon. $\endgroup$
    – Lukas Lang
    Dec 9, 2019 at 21:13

1 Answer 1

1
$\begingroup$

You can make the replacement using the downvalues.

dx = 0.02;
dz = 0.05;
Ein[j_, kz_] := 2 (j dx + kz dz);

For[kz = 1, kz < 5 + 1, kz++,
 For[j = -5, j < 5 + 1, j++,
  Ax[j, kz] = 4/5 (Ein[j + 1, kz] - Ein[j, kz])];
 DownValues[Ein] = Join[DownValues[Ein], DownValues[Ax] /. Ax -> Ein]]

vars = Cases[DownValues[Ein], 
  HoldPattern[Ein[x_Integer, y_]] :> {x, y}, Infinity]

{{-5, 1}, {-5, 2}, {-5, 3}, {-5, 4}, ... {5, 4}, {5, 5}}

Ein @@@ vars

{0.032, 0.032, 0.032, 0.032, ... 0.032, 0.032}

The results do actually come out the same, e.g.

kz = 2; j = -5;
4/5 (Ein[j + 1, kz] - Ein[j, kz]) = 4/5 (0.04 - 0.) = 0.032

kz = 1; j = -3;
4/5 (Ein[j + 1, kz] - Ein[j, kz]) = 4/5 (0.02 + 0.02) = 0.032
$\endgroup$

Your Answer

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

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