我有这个代码(*),当我这样做时:
»syms x
»newton_raphson({((5400.*(1 + x)*0^360) - (1450000.*x.*(1 + x).^360))}, diff(((5400.*(1 + x)*0^360) - (1450000.*x.*(1 + x).^360)),1), 0.001, eps, 5, 0.1)
出现此错误:
使用feval时出错 参数必须包含字符串或function_handle。
newton_raphson中的错误(第10行) fz = feval(f,z(1));
如何解决此错误?
(*)
function [raiz, zn, fz, i] = newton_raphson(f, flinha, x0, eps, iter_max, debug)
if nargin < 4
eps = 1e-6;
end
if nargin < 5
iter_max = 1e3;
end
z(1) = x0;
fz = feval(f,z(1));
fzlinha = feval(flinha,z(1));
if (nargin > 5 && debug > 0)
fprintf(2,'i=%d z=%23.18G fz=%G fzlinha=%G\n',0,x0,fz,fzlinha);
end
for i = 1:iter_max
if abs(fzlinha) == 0 % f'(x0) equal zero
disp('O valor da derivada em Xi não pode ser zero');
z(i+1) = x0;
return
end
z(i+1) = x0 - fz / fzlinha;
fz = feval(f,z(i+1));
fzlinha = feval(flinha,z(i+1));
dif = abs(z(i+1) - x0);
if (nargin > 5 && debug > 0)
fprintf(2,'i=%d z=%23.18G fz=%G fzlinha=%G dif=%E\n',i,z(i+1),fz,fzlinha,dif);
end
if dif < eps
break;
elseif i == iter_max
disp('Foi excedido o número máximo de iterações (iter_max)');
break
end
x0=z(i+1);
end
zn = z';
raiz = z(i+1);
end`
答案 0 :(得分:1)
您正在将symbolic expression传递给一个功能,该功能旨在通过它anonymous function评估function handle,name indicated by a string或Matlab路径上的函数feval
。如果您希望Matlab为您进行区分,您可以先使用符号表达式,然后通过matlabFunction
将它们转换为匿名函数
syms x f Df
%
% Symbolic expressions
f = (5400.*(1 + x)*0^360) - (1450000.*x.*(1 + x).^360);
Df = diff(f,x);
%
% Convert to anonymous functions
f = matlabFunction(f ,'Vars',x);
Df = matlabFunction(Df,'Vars',x);