I am currently trying to learn how to use ${\tt Matlab}$ properly but having a bit of trouble, I want to write a code that, say i had a differentiable function, will take as input $f$, $f'$, $x_0$ and, and return output $x_K$ for some $K$ in natural numbers $N$ such that
$$
x_k := x_{k-1} – \frac{f(x_{k-1})}{f'(x_{k-1})} \text{ for } k = 1,2,..,k \text{ and } |f(x_K)| < \epsilon.
$$
I'm guessing $f$ and $f'$ should be passed as strings, and I should use the ${\tt Matlab}$ command line. Could someone please show me how to write a code for an M-file to run this iteration?
Also, would I have to write a driver code that will call the code above and will take as inputs the functions f
,f0
(e.g., as strings or function handles, if you prefer) and x0
.
EDIT:
This is what I have written but I get errors when I try and run it,
function [] = newton1Driver1()
%% function [] = newton1Driver1()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f = inline("exp(x)-2");
df = inline("exp(x)");
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[solution,residual] = newton1(f,df,1);
error = solution-fsolve(f,1)
%% plot the log of the error vs. the steps
plot(log(error));
%% We write the output to a file, so it can be read by typesetting software
filename = sprintf("Output/newton1-1-%1.4f.csv",solution)
file = fopen(filename,"w")
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
headers = ["step $k$,","solution $x_k$,","residual $\\abs{f(x_k)}$,","error
$\\abs{x_k-\\hat x}$"]
out = [1:length(solution);solution;abs(residual);error]
fprintf(file,"%s\n",headers)
fprintf(file,"%i,%1.8e,%1.4e,%1.4e\n",out)
fprintf(file,"\n");
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fclose(filename)
Best Answer
MATLAB allows for the creation of function handles. This can be done a few ways. One approach is to explicitly define the functions:
Replace the ... with the actual form of $f$, whatever that is.
You could also do this to call it inline from the MATLAB command window
And call it with
x = testCode(1,@f,@fp);
. Note that you have to create separate function files for $f$ and $f'$.A less clunky way of doing this is through anonymous functions:
Notice that when you do it with anonymous functions vs. static files on the disk, you drop the
@
symbol.In general, you should never need to pass functions as strings. In doing so, you'd have to call into
eval
, which is bad practice and could corrupt variables unintentionally.