Search code examples
matlabcompiler-errorsargumentsnewtons-methodfunction-handle

MATLAB ERROR Feval requires a function handle as the first argument


I have this code (*) and when I do:

»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)

this error appears:

Error using feval Argument must contain a string or function_handle.

Error in newton_raphson (line 10) fz = feval(f,z(1));

How can I fix this error?

(*)

 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`

Solution

  • You are passing a symbolic expression to a function designed to evaluate an anonymous function, function handle, or a function on the Matlab path with it's name indicated by a string via feval. If you desire Matlab to do the differentiation for you, you can first use symbolic expressions and then convert them to anonymous functions via matlabFunction like this

    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);