Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I cannot find the error in my mathlab code. I need to find the roots to the func

ID: 3770964 • Letter: I

Question

I cannot find the error in my mathlab code. I need to find the roots to the function -x^3+3x^2 - 4*p, using the secant method, and plot them.

Function:

function roots=secantRoot (funName,x0,x1,tol,counterMax)
%Basic Secant method for finding the root
% funName is name of a string refering to a function
% x0 and x1 are points near the area of the root
%tol is the maximum error
%counterMaX is the maximum number of iterations
for i=1:counterMax
funx0=feval(funName,x0);
funx1=feval(funName,x1);
xi=x1-funx1*(x1-x0)/(funx1-funx0);

if abs((xi - x1)/x1)<tol
roots =xi;
break
end
x0=x1;
x1=xi;
end
if i= counterMax
fprintf('No solution found.")
  

Main:

fun = @(x)(-x^3+3x^2 - 4*p);
data[];
depth=secantRoot (fun,0,1,0.001,100)
data'= [data; p data];
end

Plot:

plot ( data[:1], data[:2])
title = ('Depth Spehere Sinks to')
xlabel= ('Density')
ylabel= ('Depth')

Explanation / Answer

%Program: demo.m

fun = @(x)(-x^3+3*x^2 - 4*x);
data=[];
p_data=[];
[data,p_data]=secantRoot(fun,0,1,0.001,100);
data=[data; p_data];
%plot
plot (data(:,1), data(:,2));
title = ('Depth Spehere Sinks to')
xlabel= ('Density')
ylabel= ('Depth')

%function: secantRoot.m

function [xi,fi] = secantRoot(f,x0,x1,tolr,nmax)
%Basic Secant method for finding the root
% funName is name of a string refering to a function
% x0 and x1 are points near the area of the root
%tolr is the maximum error
%nmax is the maximum number of iterations

% Vector of x iterates
xi = zeros(nmax+1,1);
xi(1) = x0;
xi(2) = x1;

% Vector of function values
fi = zeros(nmax+1,1);
fi(1) = f(x0);
fi(2) = f(x1);

error = tolr + 1; % error
count = 1; % iteration count

while error > tolr && count < nmax
count = count + 1;
% Find the avg slope, using xo and x1

mave = (x0*f(x1)-x1*f(x0))/(f(x1)-f(x0));
  
% Check for zero average slope: if average slope = 0, make xi, fi,
% and n equal to nan, and print out a warning, and return

if(mave==0)
x0=NaN;
% fi(x0)=NaN;
count=NaN;
disp('error');
exit;
end
% Update xo and x1 iteraterations
x0 = x1;
x1 = mave;

% Store results in vectors
xi(count+1) = x0
fi(count+1) =x1;
% Compute the error (using the last two iterates of x)
error = x(count+1)-x(count);
end
% Discard the variables you don’t need
n = count;
xi = xi(1:n+1);
fi = fi(1:n+1);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote