繁体   English   中英

如何获取函数的导数并将值放入函数中?

[英]How to get the derivative of a function and put values in the function?

我试图在Matlab中编写Newton Raphson方法,但是首先我必须找到函数的派生类。 我是Matlab的新手,但无法获得所需的结果。 我尝试了不同的方法,但无济于事,因为我对Matlab语法不熟悉,所以我没有得到想要的结果。 这是我的代码:

1)首先,我将功能保存在一个名为fun1.m的文件中

function y = fun1(x)
   y = exp(x) - 2*x - 2;

2)然后转到另一个文件,尝试编写Newton Raphson方法

%my bounds
low = 0;
high = 3;

%my initial guess will be determined from product of the function of the file fun1.m and the derivative of that function for the boundaries that i've given. If one of the products is greater then zero than this value will be my first guess. This is what I wrote

 f = fun1(x);
 f1 = diff(f);
 f2 = diff(f,2);

 %As a result if I put out the semicolons I get f1 = 0 and f2 = 0
 %I want to compute these products
 prod1 = f(low) * diff(f(low))
 prod2 = f(high) * diff(f(high))

我应该如何继续呢? 我还尝试了文件句柄,因此在区分后得到了[]。 也不必在另一个文件中包含该函数,但是因为我必须使用3个使用相同函数的方法,所以我认为从文件中获取该函数而不是每次都编写该函数会更好。 那么,如何获得该函数并将低值和高值进行区分呢?

在步骤f=fun1(x) ,f将只是位置x处f的值。 现在, diff将尝试计算向量元素之间的差异。 由于f中只有一个值,因此diff将返回[]

如果您有MATLAB Symbolic Toolbox,则可以计算符号导数。 请注意,这些函数仍称为diff ,但是它们是不同的函数! 有关详细信息,请比较MATLAB DiffSymbolic Diff函数的帮助页面。

syms x
f = exp(x) - 2*x - 2;
df = diff(f);
ddf = diff(df);

然后您可以在需要的时候评估这些功能

prod1 = subs(f,x,low) * subs(df,x,low);
prod2 = subs(f,x,high) * subs(df,x,low);

现在prod1prod2仍然是象征性的数字,而不是“正常”的双重价值。 在此示例情况下, prod2=8-exp(3) prod1=1prod2=8-exp(3) 要将数字转换为双倍,只需

p1 = double(prod1);
p2 = double(prod2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM