Matlab "for" vs "while"

359 Views Asked by At

I am trying to solve the system by Jacobi method.

\begin{align*} 5x-y+z&=10\\ 2x+8y-z&=11\\ -x+y+4z&=3 \end{align*}

So I wrote the following Matlab code.

enter image description here enter image description here enter image description here Now when I run this, only one iterate is given. But I am expecting multiple iterates approaching exact solution.

But when I use "for" loop, it gives multiple iterates. enter image description here

What am I doing wrong with "while" loop?

1

There are 1 best solutions below

0
On BEST ANSWER

At the end of your while loop, you set x0=x which means that x-x0=0 up to machine precision. This means that norm(x-x0)=norm(0) which will obviously satisfy the while condition and break from the loop. Your for loop does not have this problem, since you compute x before setting it equal to x0 with your if comparison. Basically, your while loop should work if you switch the order of your two statements.