galipnik
(gabse15 l)
1
Hey!
I’m trying to implement the Jacobi iteration in Mathematica, but it does not work… I’m a beginner in Mathematica, can anybody help?
Here’s my code:
jac[A_, b_, xstart_] := Module[{n, k, i, j, xneu, xalt},
n = Length[b];
xalt = xstart;
While[k < 10000,
xneu = b;
For[i = 1, i <= n, i++,
For[j = 1, j <= n, j++,
If[i != j,
xneu[[i]] = xneu[[i]] - A[[i, j]]*xalt[j];
]
]
xneu[[i]] = xneu[[i]]/A[[i, i]];
]
xalt = xneu;
k++;
]
Return[xalt];
];
jbaldwin
(Jim Baldwin)
2
What exactly doesn’t work? Do you get an error? What input did you use?
galipnik
(gabse15 l)
3
My input is:
A = {{10, 14, 11}, {13, -66, 14}, {11, -13, 12}}; b = {1, 1, 1}; xstart = {0, 0, 0}; Print[jac[A, b, xstart]];
Output is nothing. What am I doing wrong?
Edit: Outpus is jac[{{10,14,11},{13,-66,14},{11,-13,12}},{1,1,1},{0,0,0}].
jbaldwin
(Jim Baldwin)
4
Here are two items that need fixing (but there are more things to fix):
k needs to be initialized.
- There is an instance of
xalt[j] that should be xalt[[j]].
jbaldwin
(Jim Baldwin)
5
Does this do what you want? (I’ve reduced the number of iterations to 10 to minimize the output.)
jac[A_, b_, xstart_] := Module[{n, k, i, j, xneu, xalt},
n = Length[b];
xalt = xstart;
k = 0;
While[k < 10,
xneu = b;
For[i = 1, i <= n, i++,
For[j = 1, j <= n, j++,
If[i != j, xneu[[i]] = xneu[[i]] - A[[i, j]]*xalt[[j]]]];
xneu[[i]] = xneu[[i]]/A[[i, i]]];
xalt = xneu;
k++];
xalt];
A = {{10, 14, 11}, {13, -66, 14}, {11, -13, 12}};
b = {1, 1, 1};
xstart = {0, 0, 0};
jac[A, b, xstart]
(* {1382598113217283/36067178188800000,
379022657204357/22132132070400000,
-(4712310469911859/486906905548800000)} *)