1

I wrote my very first octave script which is a code for the incremental search method for root finding but I encountered numerous errors that I found hard to understand. The following is the script:

clear 

syms x;

fct=input('enter your function in standard form: ');
f=str2func(fct); % This built in octave function creates functions from strings
Xmax=input('X maximum= ');

Xinit=input('X initial= ');

dx=input('dx= ');
epsi=input('epsi= ');
N=10; % the amount by which dx is decreased in case a root was found.

while (x<=Xmax)
    
    f1=f(Xinit);
    x=x+dx
    f2=f(x);
    if (abs(f2)>(1/epsi))
        disp('The function approches infinity at ', num2str(x));
        x=x+epsi;
    else
        if ((f2*f1)>0)
          x=x+dx;
    elseif ((f2*f1)==0)
        disp('a root at ', num2str );
        x=x+epsi;
    else
        if (dx < epsi)
          disp('a root at ', num2str);
          x=x+epsi;
        else
            x=x-dx;
            dx=dx/N;
            x=x+dx;
        end
    end
end
end  

when running it the following errors showed up:

>> Incremental

enter your function in standard form: 1+(5.25*x)-(sec(sqrt(0.68*x)))
warning: passing floating-point values to sym is dangerous, see "help sym"
warning: called from
    double_to_sym_heuristic at line 50 column 7
    sym at line 379 column 13
    mtimes at line 63 column 5
    Incremental at line 3 column 4
warning: passing floating-point values to sym is dangerous, see "help sym"
warning: called from
    double_to_sym_heuristic at line 50 column 7
    sym at line 379 column 13
    mtimes at line 63 column 5
    Incremental at line 3 column 4
error: wrong type argument 'class'
error: str2func: FCN_NAME must be a string
error: called from
    Incremental at line 4 column 2

Below is the flowchart of the incremental search method: enter image description here

desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

0

The problem happens in this line:

fct=input('enter your function in standard form: ');

Here input takes the user input and evaluates it. It tries to convert it into a number. In the next line,

f=str2func(fct)

you assume fct is a string.

To fix the problems, tell input to just return the user's input unchanged as a string (see the docs):

fct=input('enter your function in standard form: ', 's');
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120