Why does this SIMPLE code not work

1 回表示 (過去 30 日間)
Mak
Mak 2017 年 5 月 25 日
編集済み: Moe_2015 2017 年 5 月 25 日
The first and last f1 return the same result, even though x has been changed along the way. Why is this and how to fix it?
x = 1.5
f1= sin(x) + x*cos(x)
f2 = 2*cos(x)-x*sin(x)
x = x - (f1/f2)
f1
Thank you in advance!

回答 (1 件)

Moe_2015
Moe_2015 2017 年 5 月 25 日
In the last line, you are just printing to the screen the result you got in the 2nd line. If you want f1 to be calculated again you need to do so.
x = 1.5
f1= sin(x) + x*cos(x)
f2 = 2*cos(x)-x*sin(x)
x = x - (f1/f2)
f1_new = sin(x) + x*cos(x) % renamed so you can see that it is different than the original f1.
  2 件のコメント
Mak
Mak 2017 年 5 月 25 日
Thanks! I was thinking it might be something like that. I just find it completely illogical. The system should not work like that, but instead always recalculate it. Weird...
Moe_2015
Moe_2015 2017 年 5 月 25 日
編集済み: Moe_2015 2017 年 5 月 25 日
If you want it to work like that you can create an anonymous function making f1 a function handle like this (and f2 also just to remain consistent):
x = 1.5;
f1= @(x) sin(x) + x*cos(x);
f1(x)
f2 = @(x) 2*cos(x)-x*sin(x);
x = x - (f1(x)/f2(x))
f1(x)

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

カテゴリ

Help Center および File ExchangeGeneral Applications についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by