Help with creating a Newton-Raphson algorithm function

As a part of a MATLAB course I've been asked to create a function that will solve a mathematical function by using Newton-Raphson algorithm.
So I've written the following function:
function s=newtRaph(Y,x1)
syms x
y=diff(Y,x);
Y=subs(Y,x,x1);y=subs(y,x,x1);
for i=1:4
xx=x1-(Y/y);
x1=xx;
end
s=x1;
And called it in the script like so:
syms x
y=x-cos(x);
newtRaph(y,3)
The problem is that i get the following ans instead of the solution:
ans =
(4*(cos(3) - 3))/(sin(3) + 1) + 3
Can anyone tell me what am I doing wrong?

 採用された回答

madhan ravi
madhan ravi 2018 年 11 月 17 日

0 投票

Can anyone tell me what am I doing wrong?
Since you created a function with a single output you have to also call it with an output .
as below:
Solution=newtRaph(y,3)

5 件のコメント

IKIK
IKIK 2018 年 11 月 17 日
The problem is not that it called "ans", the problem is that I need to get a single number as an answer (around 0.7)
madhan ravi
madhan ravi 2018 年 11 月 17 日
Try
double(Solution)
IKIK
IKIK 2018 年 11 月 17 日
編集済み: IKIK 2018 年 11 月 17 日
Maybe that is the solution but it is way beyond my level of understanding.
Thank you for your help
madhan ravi
madhan ravi 2018 年 11 月 17 日
編集済み: madhan ravi 2018 年 11 月 17 日
Anytime :) ,If it helped you make sure to accept the answer

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

その他の回答 (1 件)

Greg Heath
Greg Heath 2018 年 11 月 17 日
編集済み: Greg Heath 2018 年 11 月 17 日

0 投票

Add the line
ans = ans
Hope this helps.
Thank you for formally accepting my answer
Greg

カテゴリ

ヘルプ センター および File ExchangeSymbolic Math Toolbox についてさらに検索

質問済み:

2018 年 11 月 17 日

編集済み:

2018 年 11 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by