Calling a function for an array of inputs

So I'm trying to complete this code that utilizes the Newton Raphson method to solve the Rachford-Rice equation. My Newton Raphson function is:
function [x, i]=NewtonRaphson(func, dfunc, v_0, tolerance)
%a function to find the roots of a function, f, using the NewtonRaphson
%method. Outputs the roots and iterations
clear;clc;
i=1; %first iteration is initialized
x(i)=v_0; %the value of the function input at the first index is declared
while abs(func(x(i)))>tolerance %a while loop to determine if the the function evaluated at the iterated input is within tolerance
fprintf('During iteration %d, a value of x=%.2f yielded f=%.2E\n',i,x(i),func(x(i))) %prints the iterations, root, and function evaluated at that root
x(i+1)=x(i)-func(x(i))./df(x(i)); %Newton Raphson method
i=i+1; %iteration increased by 1 at the end of the cycle
end
fprintf('During iteration %d, a value of x=%.2f yielded f=%.2E\n Convergence is within tolerance.\n',i,x(i),f(x(i))) %prints the final value of the function and root and the last iteration
end
I've also created a script file to feed inputs to the function:
F=[20; 30; 50];
K=[3.7; 1.4; 0.6];
tol=0.0001;
z=zeros(1, length(K));
v_initial=0.6;
for n=(1:length(F))
z(n)=F(n)/100;
f=@(v)((K(n)-1).*z(n))/(1+(K(n)-1)*v);
df=@(v) z(n)*LOG(v);
NewtonRaphson(f, df, v_initial, tol)
end
Whenever I try to run this, I get an error stating that I have too many input arguments. Originally I called the function outside of the for loop, got that error, put the function I defined and the call to NewtonRapshon within the for loop and still receive that error. What am I doing wrong? I believe my NewtonRaphson function is alright, but something I'm doing in this script is causing an error and I have a hunch it's the array of values I'm feeling into it with the for loop.

3 Comments

Please check if you have any other function named 'NewtonRaphson'. You can do so by using the following command:
whcih -all NewtonRaphson
You need to get rid of the
clear;clc;
inside your function.
You have the following issues with your code :
1. Get rid of 'clear' and 'clc' commands from within your 'NewtonRaphson' function
2. Line 11 in your driver code should be the following :
df=@(v) z(n)*log(v);
instead of
df=@(v) z(n)*LOG(v);
Note: MATLAB is case-sensitive and there is no function called LOG in MATLAB.
3. Line 9 in 'NewtronRaphson' function should be the following :
x(i+1)=x(i)-func(x(i))./dfunc(x(i)); %Newton Raphson method
and not
x(i+1)=x(i)-func(x(i))./df(x(i)); %Newton Raphson method
Making the above changes will get rid of all your compiler errors.
Hope it helps,
Best Regards,
Vaidyanathan

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!