如何在 MATLAB 中为 Newton Raphson 方法编写输入函数的微分
How to find differential of input function while writing in MATLAB for Newton Raphson method
我一直在寻找一种方法来区分用户输入的函数,并根据牛顿拉夫森法对它进行微分,但是由于不推荐使用内联函数,有什么方法可以取用户的然后输入符号函数?我尝试将 inline 转换为 sym 但此代码:
a=input('Enter function with right hand side zero:','s');
x(1)=input('Enter Initial Guess:');
Es=input('Enter allowed Error:');
f=inline(a)
dif=diff(sym(a));
d=inline(dif);
for i=1:100
x(i+1)=x(i)-((f(x(i))/d(x(i))));
err(i)=abs((x(i+1)-x(i))/x(i));
if err(i)<error
break
end
end
disp(x(i));
在接受每个参数后给出此错误:
Error using sym>convertChar (line 1557)
Character vectors and strings in the first
argument can only specify a variable or
number. To evaluate character vectors and
strings representing symbolic expressions, use
'str2sym'.
Error in sym>tomupad (line 1273)
S = convertChar(x);
Error in sym (line 229)
S.s = tomupad(x);
Error in Newton_Raphson (line 6)
dif=diff(sym(a));
我看到有很多人以前遇到过同样的困难,我也尝试了这些解决方案,就像我也尝试使用 str2sym
一样,但是它在包含差异的行上抛出了同样的错误。我错过了什么吗?我是 MATLAB 世界的新手。
使用函数 str2func()
、sym()
和 matlabFunction()
可以将参数转换为 diff()
函数所需的适当输入类型。下面是一个小的 test/playground 脚本,它接受一个由 @()
指示的匿名函数,指示相关的 variables/input 变量。
• str2func()
:从字符串转换为→匿名函数(函数句柄)
• sym()
:从匿名函数(函数句柄) → 符号函数
转换
• matlabFunction:
从符号函数转换为匿名函数(函数句柄)
a = input('Enter function with right hand side zero:','s');
f = str2func(a);
dif = diff(sym(f));
d = matlabFunction(dif);
%Testing that the function handles (anonymous functions) work%
f(5)
d(2)
运行 使用 MATLAB R2019b
我一直在寻找一种方法来区分用户输入的函数,并根据牛顿拉夫森法对它进行微分,但是由于不推荐使用内联函数,有什么方法可以取用户的然后输入符号函数?我尝试将 inline 转换为 sym 但此代码:
a=input('Enter function with right hand side zero:','s');
x(1)=input('Enter Initial Guess:');
Es=input('Enter allowed Error:');
f=inline(a)
dif=diff(sym(a));
d=inline(dif);
for i=1:100
x(i+1)=x(i)-((f(x(i))/d(x(i))));
err(i)=abs((x(i+1)-x(i))/x(i));
if err(i)<error
break
end
end
disp(x(i));
在接受每个参数后给出此错误:
Error using sym>convertChar (line 1557)
Character vectors and strings in the first
argument can only specify a variable or
number. To evaluate character vectors and
strings representing symbolic expressions, use
'str2sym'.
Error in sym>tomupad (line 1273)
S = convertChar(x);
Error in sym (line 229)
S.s = tomupad(x);
Error in Newton_Raphson (line 6)
dif=diff(sym(a));
我看到有很多人以前遇到过同样的困难,我也尝试了这些解决方案,就像我也尝试使用 str2sym
一样,但是它在包含差异的行上抛出了同样的错误。我错过了什么吗?我是 MATLAB 世界的新手。
使用函数 str2func()
、sym()
和 matlabFunction()
可以将参数转换为 diff()
函数所需的适当输入类型。下面是一个小的 test/playground 脚本,它接受一个由 @()
指示的匿名函数,指示相关的 variables/input 变量。
• str2func()
:从字符串转换为→匿名函数(函数句柄)
• sym()
:从匿名函数(函数句柄) → 符号函数
转换
• matlabFunction:
从符号函数转换为匿名函数(函数句柄)
a = input('Enter function with right hand side zero:','s');
f = str2func(a);
dif = diff(sym(f));
d = matlabFunction(dif);
%Testing that the function handles (anonymous functions) work%
f(5)
d(2)
运行 使用 MATLAB R2019b