Need help with looping a simple linear system

2 views (last 30 days)
Hi, I have a problem looping a piece of code, I get weird errors from using while or I'm making a mistake, I don't know at this time, but I could really use a hand.
Basically, my program calculates functions f and g, which are function of x,y and m; m is fixed at 0.25 and I need to find the values of x and y for which functions f and g near zero.
Here's the code:
x=0; y=1; m=0.25; tol=0.05; f=0; g=0; %values for x and y are just for initialization, m remains 0.25 %throughout; I chose a tolerance of 0.05, but it could be different; %functions f and g are initialized as null
f=m-y*sin(x); g=m+2*y^2-2*y*cos(x);
%functions f and g are calculated with initial values for x,y,m
dfg=[f g]';
%dfg is a column vector for f and g values
J=[-y*cos(x) -sin(x); 2*y*sin(x) 4*y-2*cos(x)];
%here the Jacobian matrix is calculated, which contains partial %differentials for functions f and g, each in relation to x and y; %J=[df/dx df/dy; dg/dx dg/dy];
dxy=(J^(-1))*dfg;
%dxy is the deviation vector, the multiple of the inverted J matrix %and the value vector for the two functions f and g
x=x+dxy(1); y=y+dxy(2);
%here x and y are adjusted by adding the corresponding values from %the deviation vector
Now, what I need the program to do is loop, as in run until the function values are smaller than the tolerance (dfg(1) and dfg(2) < tol (tol is adjustable, but should be small, near zero)). I've tried while and for and I get weird errors for them, but I could just simply be doing it wrong :)
Please help me and tell me how to loop this thing until f,g < tol
[code] x=0; y=1; m=0.25; tol=0.1; f=0; g=0;
f=m-y*sin(x); g=m+2*y^2-2*y*cos(x); dfg=[f g]'; J=[-y*cos(x) -sin(x); 2*y*sin(x) 4*y-2*cos(x)]; dxy=(J^(-1))*dfg; x=x+dxy(1); y=y+dxy(2);
[/code]

Accepted Answer

Matt Tearle
Matt Tearle on 27 Feb 2011
  1. I assume this is some kind of hw/exercise. If not, use a MATLAB root-finder, rather than writing your own.
  2. As proecsm notes, x_[n+1] = x_[n] - J(x)\F(x) (not +)
  3. Speaking of which, never use an inverse. Use backslash: dxy=J\dfg;
  4. Wrap the middle chunk of the code in a while loop. Define f & g to be greater than the tolerance, to ensure it runs at least once (or actually evaluate them, to see if you happen to have guessed the root).
  5. The condition for the while loop is up to you (and/or the instructions on the problem). You might want to use the norm function, though.
So, given that you mention using while, maybe you could give us the code and/or the problem you're getting as a result.

More Answers (1)

bym
bym on 27 Feb 2011
maybe you should change x & y to
x = x-dxy(1);
y = y-dxy(2);
  1 Comment
Radu Mihai
Radu Mihai on 27 Feb 2011
thanks! I hadn't noticed that, doing too many things at once :)

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!