I want to use Gauss-Seidel iteration to solve this problem.
$$\left\{\begin{array}{l} 8 x_{1}-3 x_{2}+2 x_{3}=20 \\ 4 x_{1}+11 x_{2}-x_{3}=33 \\ 6 x_{1}+3 x_{2}+12 x_{3}=36 \end{array}\right.$$
n = 3;
b = {20, 33, 36}; a = {{8, -3, 2}, {4, 11, -1}, {6, 3, 12}};
Δx[
i_] := (b[[i]] - Sum[a[[i, j]]*x[j, k], {j, 1, i - 1}] -
Sum[a[[i, j]]*x[j, k - 1],
{j, i + 1, n}])/a[[i, i]]
Thread[Table[x[i, k], {i, 1, n}] ==
Table[Δx[i], {i, 1, n}]]
I want to be able to use Table[Hold[x[i, k_] := x[i, k] = Δx[i]], {i, 1, n}]
to automatically define functions instead of manually defining related functions as follows:
x[1, k_] := x[1, k] = (1/8)*(3*x[2, k - 1] - 2*x[3, k - 1] + 20)
x[2, k_] := x[2, k] = (1/11)*(-(4*x[1, k ]) + x[3, k - 1] + 33)
x[3, k_] := x[3, k] = (1/12)*(-(6*x[1, k ]) - 3*x[2, k ] + 36)
That is, I want to use function Table
to automatically define some functions.
So that the following operations can be carried out automatically:
x[1, 0] = 1.;
x[2, 0] = 1.;
x[3, 0] = 1.;
Table[{x[1, i], x[2, i], x[3, i]}, {i, 0, 10}]
LinearSolve[( {
{8, -3, 2},
{4, 11, -1},
{6, 3, 12}
} ), {20, 33, 36}]
What can I do to get the custom functions directly in the result?
Update 1:
The following code can implement batch custom functions:
Table[With[{i = i}, Hold[x[i, k_] := x[i, k] = i*k]], {i, 1, 3}]
ReleaseHold[%]
Table[{x[1, i], x[2, i], x[3, i]}, {i, 0, 3}]
But I don't know why the following code doesn't work in the same way:
n = 3;
b = {20, 33, 36}; a = {{8, -3, 2}, {4, 11, -1}, {6, 3, 12}};
Δx[i_] := (b[[i]] - Sum[a[[i, j]]*x[j, k], {j, 1, i - 1}] -
Sum[a[[i, j]]*x[j, k - 1], {j, i + 1, n}])/a[[i, i]]
Table[With[{i = i},
Hold[x[i, k_] := x[i, k] = Δx[i]]], {i, 1, 3}]
ReleaseHold[%]
Table[{x[1, m], x[2, m], x[3, m]}, {m, 0, 1}]
I guess the local assignment of k
may cause this problem, but I don't know how to solve this problem. Please help me.
Table[With[{i = i}, Hold[...i...]], {i, n}]
maybe. See docs forWith
, underScope
. $\endgroup$Table
andHold
, and you needWith
to insert the value ofi
, as I showed. It does exactly what I would want it to do. If it doesn't work for you, I can only think you don't know whatHold
does and decided to stick it in for no reason. What happens if you leave it out or useReleaseHold
? $\endgroup$