Why are these interations not working?

3 vues (au cours des 30 derniers jours)
Scott Banks
Scott Banks le 3 Juin 2024
Commenté : Scott Banks le 6 Juin 2024
Hi there,
I am trying to perform simple iterations to solve a pair of simultaneous equations. However, I am not getting the correct results when using a for loop. My code looks like this:
syms x y
eq1 = 2*x + y == 16
eq1 = 
eq2 = 5*y - x == 25
eq2 = 
x1 = 16/2;
y1 = 25/5;
fyx = -1/2;
fxy = 1/5;
x2 = fyx*y1
x2 = -2.5000
y2 = fxy*x1
y2 = 1.6000
x3 = fyx*y2
x3 = -0.8000
y3 = fxy*x2
y3 = -0.5000
x4 = fyx*y3
x4 = 0.2500
y4 = fxy*x3
y4 = -0.1600
for i = 1:4
x2 = fyx*y1
y2 = fxy*x1;
y1 = x2;
x1 = y2;
end
x2 = -2.5000
x2 = 1.2500
x2 = -0.6250
x2 = 0.3125
Outside the loop the iterations are giving the correct answer. That is x2, x3, x4 = -2.50, -0.80, 0.250 respectively, and y2, y3, y4, 1.69, -0.50, -0.160 repectively.
But in the loop for x2, x3, x4 is 2.50, 1.250, -0.6250...
Am I doing something incorrect in my for loop to get these incorrect results?
Many thanks in adavance!

Réponse acceptée

Torsten
Torsten le 3 Juin 2024
x1 = 16/2;
y1 = 25/5;
fyx = -1/2;
fxy = 1/5;
x2 = fyx*y1
x2 = -2.5000
y2 = fxy*x1;
x3 = fyx*y2
x3 = -0.8000
y3 = fxy*x2;
x4 = fyx*y3
x4 = 0.2500
y4 = fxy*x3;
for i = 1:3
x2 = fyx*y1
y2 = fxy*x1;
y1 = y2;
x1 = x2;
end
x2 = -2.5000
x2 = -0.8000
x2 = 0.2500
  1 commentaire
Scott Banks
Scott Banks le 6 Juin 2024
Thanks for that, Torsten!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by