I have a code (below) using the Secant Method to evaluate a function f(x) = exp(x) – 3*x^2 with p_0 = 3, p_1 = 5, and a tolerance of 1e-5. As is, the code runs exceedingly slow. It seems to get worse with each iteration, but if I replace lines 22, 24, and 41 with an evaluation of '= double(subs(g))', then it has a much, much faster turnaround time. What is happening when MATLAB tries to evaluate line 28 with a 1×1 sym that makes it so much slower?
%% Inputs
syms x;fprintf(1,'Input the function g(x) in terms of x.\n');fprintf(1,'For example: cos(x) \n');s = input('');g = @(x) s; %user-input function
fprintf(1,'Input the initial approximation to P0.\n');p_0 = input(''); %initial approximation
fprintf(1,'Input the initial approximation to P1.\n');p_1 = input(''); %initial approximationfprintf(1,'Input the desired tolerance.\n');tol = input(''); %allowable absolute error
fprintf(1,'Input the maximum iterations.\n');n = input(''); %max iterations
i = 2; %initialize counting variable
x = p_0;q_0 = subs(g);x = p_1;q_1 = subs(g);%% Secant Method
while i <= n p = p_1 - q_1*(p_1- p_0)/(q_1 - q_0); tol_n = abs(p - p_1); if tol_n < tol fprintf(['p = %.8f after %d iterations with a tolerance of %.0e'... ',\nwhich is less than the specified tolerance of %e'], p,... i, tol_n, tol); return else i = i + 1; p_0 = p_1; q_0 = q_1; p_1 = p; x = p; q_1 = subs(g); endend%% Error
fprintf(['The method failed after %d iterations with a value of\n p'... ' = %.8f\nand a tolerance of %.8f\n'], i-1, p,tol_n);
Best Answer