This is my first time writing code using varargin, so appologies if I'm doing it completely wrong.
I'm trying to keep it as general as possible, and the function file is below.
For example, say I set the inputs as
fun = @(x, Q) x^3 + Q
xi=[-1, -2]
es= 10^-5
max_it=50
If I want to send Q=7 through varargin, how would I set it up, both in the function file and the line of code I call it from?
function [xroot,residual,ea,iter_count] = root_finder(fun,xi,es,max_it,varargin)%Inputs
% fun - The function to examine
% xi - A vector containing the inital guesses for the root value
% es - Stopping criteria. How close you want it to calculate to. Default is 0.00001
% max_it - Maximum number of times the program will run. Default is 30
% varagin - Any other criteria needed for the function
%Outputs
% xroot - Root estimate
% residual - The residual of the function
% ea - The relative error
% iter_counter - number of iterations you went through
if isempty(es) %Sets stopping criteria default to 10^-5
es = 10^-5;endif isempty(max_it) %Sets maximum iteration count default to 30
max_it = 30;endfor loops=1:max_it; fun_at_x1 = fun(xi(1)); %Finds residual of function at each guess
fun_at_x2 = fun(xi(2)); %
new_root = xi(2) - fun_at_x2 * ((xi(2) - xi(1)) / (fun_at_x2 - fun_at_x1)); %Calculates new root to check function at using Newtons Method
fun_at_new_root = fun(new_root); %Calculates function at the new root
xi= [xi(2) new_root]; %Sets xi to store the two most recently tested roots
if abs(fun_at_new_root) < es %If the residual of the function at new_root is within the stopping criteria, exit the for loop
break endend xroot=new_root residual = fun_at_new_root iter_count = loops ea = (xi(2) - xi(1)) / xi(2) end
Best Answer