【问题标题】:How to get the derivative of a function and put values in the function?如何获得函数的导数并将值放入函数中?
【发布时间】:2014-12-23 18:30:24
【问题描述】:

我正在尝试在 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 个使用相同函数的方法,所以我认为从文件中获取函数而不是每次都编写它会更好。那么如何获取函数并设置低值和高值并区分它们呢?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    在步骤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 仍然是符号数字,而不是“正常”的双精度值。在本例中,prod1=1prod2=8-exp(3)。要将数字转换为双精度,只需

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

    【讨论】:

    • 它似乎有效,但我不明白最后一部分。即使没有将产品转换为双倍,我也会得到 prod1=1 和 prod2= 218.5734
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多