Why are these interations not working?

1 回表示 (過去 30 日間)
Scott Banks
Scott Banks 2024 年 6 月 3 日
コメント済み: Scott Banks 2024 年 6 月 6 日
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!

採用された回答

Torsten
Torsten 2024 年 6 月 3 日
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 件のコメント
Scott Banks
Scott Banks 2024 年 6 月 6 日
Thanks for that, Torsten!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeConversion Between Symbolic and Numeric についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by