Matlab help Newton Rapshon method [duplicate] - matlab

This question already has answers here:
Newton-Raphson Method in Matlab
(2 answers)
Closed 6 years ago.
If I have a code like this
funk=#(x) x2-4;
dfunk=#(x) 2*x;
xk=4;
for i = 1:5
xk+i= xk-funk(of what? xk or #(x) x2-4) / dfunk( same problem here);
end
I do not know what am I supposed to write in brackets it is supposed to be Newton Raphson method.
Thanks for help

You should not add i to your xk in the for loop. As Newton's Metod
generates a series which converges to a root of the funktion the +i only operates on the indices of the series.
Your code should look like this.
funk = #(x) x^2-4;
dfunk = #(x) 2*x;
xk = 4;
for i=1:5
xk = xk - funk(xk)/dfunk(xk)
end
Anyway I would not recommend to use a fixed condition like i=1:5 but something like
TOL = 10e-4;
DIFF = 1; % something larger than TOL
funk = #(x) x^2-4;
dfunk = #(x) 2*x;
xk = 4;
while (DIFF > TOL)
aux = xk - funk(xk)/dfunk(xk);
DIFF = abs(xk-aux);
xk = aux;
end

Related

MatLab input argument error with objective function and fmincon()

I am working through an example using fmincon().
I define my objective function in objFun.m
function f=objFun(x)
f = 100*(x(2) - (x(1))^2)^2 + (1 - x(1))^2;
end
and I define an initial point x0
x0=[1; -1]
And if I run the objective function with that point as a test I get
>> objFun(x0)
ans =
400
But when I try to use it in fmincon() I get
>> [x, fval] = fmincon(objFun, x0, [1;2],1,[],[],[0; -inf],[inf, 0]);
Not enough input arguments.
Error in objFun (line 2)
f = 100*(x(2) - (x(1))^2)^2 + (1 - x(1))^2;
I suspect I'm missing something very simple here, but what?
you need to pass a handle to the function #objFun not the function itself, and your A and x0 matrix need to be transposed, ie: a row with 2 columns, each row in A is another linear constraint.
x0=[1, -1];
A = [1,2];
b = 1;
[x, fval] = fmincon(#objFun, x0, A,b,[],[],[0; -inf],[inf; 0]);
function f=objFun(x)
f = 100*(x(2) - (x(1))^2)^2 + (1 - x(1))^2;
end

I can't see the output of my Matlab code for Newton's Method, what am I missing? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
So I have the following matlab code where I am attempting to calculate Newton's Method to solve a non-linear equation (in particular, identify the square root). I am unable to see the output of my two fprintf() statements, so I think I fundamentally misunderstand MATLAB's way of calling functions.
I feel that there is something so fundamentally basic that I missing here.
I am running this over the Matlab web application https://matlab.mathworks.com/
My code is the following:
clear all
p = 81; %set to whatever value whose square root you want to find.
egFun = # (x) x^2 - p;
egFunDer = # (x) 2*x;
firstGuess = p;
Err = 0.00001;
imax = 20;
%% (+) function, functionDervivate, X-estimate, Error, i-Maximum (-) X-Solution
function Xsolution = NewtonRoot(Fun, FunDer, Xest, Err, imax)
for i = 1 : imax
fprintf("test %f", i)
% below is the newton's method formula in action
Xi = Xest - Fun(Xest)/FunDer(Xest)
% let Xest be replaced with our new value for X so that we can
% perform the next iteration
if(abs(0-Fun(Xi)) <= Err)
Xsolution = Xi;
break
end
Xest = Xi
end
Xsolution = Xi;
end
%%
function answer = main
answer = NewtonRoot(egFun, egFunDer, firstGuess, Err, imax)
fprintf("the Solution is %f", answer)
end
I expect to see a value for answer, which should print to the console, as well as the two fprintf() statements I threw in for debugging.
You need to call NewtonRoot function in main code.
clear all
p = 81; %set to whatever value whose square root you want to find.
egFun = # (x) x^2 - p;
egFunDer = # (x) 2*x;
firstGuess = p;
Err = 0.00001;
imax = 20;
%%
answer = NewtonRoot(egFun, egFunDer, firstGuess, Err, imax)
fprintf("the Solution is %f", answer)
%% (+) function, functionDervivate, X-estimate, Error, i-Maximum (-) X-Solution
function Xsolution = NewtonRoot(Fun, FunDer, Xest, Err, imax)
for i = 1 : imax
fprintf("test %f", i)
% below is the newton's method formula in action
Xi = Xest - Fun(Xest)/FunDer(Xest)
% let Xest be replaced with our new value for X so that we can
% perform the next iteration
if(abs(0-Fun(Xi)) <= Err)
Xsolution = Xi;
break
end
Xest = Xi
end
Xsolution = Xi;
end

how to find satistics of the fitted parameter of an equation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
For instance: a, b, c and n are the three constants, which are required to be calculated by using data fitting method in a particular equation.
How can I calculate the statistics (mean, standard deviation, variance, skewness value and student t-test value) of the parameters as of a custom equation, for example the quadratic plateau equation?
Example:
x=[0,40,80,100,120,150,170,200],
y=[1865,2855,3608,4057,4343,4389,4415,4478]
y=a*(x+n)^2+b*(x+n)+c, x < xc(Ymax) ....(1) y=yp, x >= xc(Ymax) ....(2)
I have fitted this equation by given code:
yf = #(b,x) b(1).*(x+n).^2+b(2)*(x+n)+b(3); B0 = [0.006; 21; 1878];
[Bm,normresm] = fminsearch(#(b) norm(y - yf(b,x)), B0); a=Bm(1);
b=Bm(2); c=Bm(3); xc=(-b/(2*a))-n; p=p=a*(xc+n)^2+b*(xc+n)+c;
if (x < xc)
yfit = a.*(x+n).^2+ b*(x+n)+c;
else
yfit = p;
end
plot(x,yfit,'*')
hold on; plot(x,y); hold off
Note: I have already used the polyfit command, it was helpful and provided me the results. However, I really don’t find it suitable, as there is no option to customize the equation. Can I find these statistics by any code?
Questions 1, 2 and 4)
Good practice is to set initial values close to the final result if you have previous knowledge about the equation system:
What you have is an overdetermined system of linear equations.
y(1) = a*x(1)^2 + b*x(1) + c
y(2) = a*x(2)^2 + b*x(2) + c
y(3) = a*x(3)^2 + b*x(3) + c
…
y(n) = a*x(n)^2 + b*x(n) + c
or in general:
y = A*X, where
A = [a; b; c]
X = [x(1)^2 x(1) 1;
x(2)^2 x(2) 1;
x(3)^2 x(2) 1;
...
x(n)^2 x(n) 1]
One of the common practices to fit the overdetermined system (since it has no solution) is "least square fit" (mldivide,\ (link))
x=[0; 40; 80; 100; 120; 150; 170; 200];
y=[1865; 2855; 3608; 4057; 4343; 4389; 4415; 4478];
X = [x.^2 x ones(numel(x),1)];
A = y\X;
a0=A(1); %- initial value for a
b0=A(2); %- initial value for b
c0=A(3); %- initial value for c
You can customize equation, when you customize your X and A
but you also can set initial values to ones, it should have neglectable small impact on the result. More related to Question 4
a0=1;
b0=1;
c0=1;
or to random values
rng(10);
A = rand(3,1);
a0=A(1);
b0=A(2);
c0=A(3);
Question 3 - Statistics
If you need more control on monitoring of optimization process, use more general form of writing anonymous function (in code below> myfun) to save all intermediate values of parameters (a_iter, b_iter, c_iter)
function Fiting_ex()
global a_iter b_iter c_iter
a_iter = 0;
b_iter = 0;
c_iter = 0;
x=[0; 40; 80; 100; 120; 150; 170; 200];
y=[1865; 2855; 3608; 4057; 4343; 4389; 4415; 4478];
X = [x.^2 x ones(numel(x),1)];
A = y\X;
a0=A(1);
b0=A(2);
c0=A(3);
B0 = [a0; b0; c0];
[Bm,normresm] = fminsearch(#(b) myfun(b,x,y),B0);
a=Bm(1);
b=Bm(2);
c=Bm(3);
xc=-b/(2*a);
p=c-(b^2/(4*a));
yfit = zeros(numel(x),1);
for i=1:numel(x)
if (x(i) < xc)
yfit(i) = a.*x(i).^2+ b*x(i)+c;
else
yfit(i) = p;
end
end
plot(x,yfit,'*')
hold on;
plot(x,y);
hold off
% Statistic on optimization process
a_mean = mean(a_iter(2:end)); % mean value
a_var = var(a_iter(2:end)); % variance
a_std = std(a_iter(2:end)); % standard deviation
function f = myfun(Bm, x, y)
global a_iter b_iter c_iter
a_iter = [a_iter Bm(1)];
b_iter = [b_iter Bm(2)];
c_iter = [c_iter Bm(3)];
yf = Bm(1)*(x).^2+Bm(2)*(x)+Bm(3);
a=Bm(1);
b=Bm(2);
c=Bm(3);
xc=-b/(2*a);
p=c-(b^2/(4*a));
yfit = zeros(numel(x),1);
for i=1:numel(x)
if (x(i) < xc)
yfit(i) = a.*x(i).^2+ b*x(i)+c;
else
yfit(i) = p;
end
end
f = norm(y - yfit);

Matlab: Repeat iteration until condition is met

I am trying to learn Matlab as someone with an R background. I have the following program written for an iteration that I would like to repeat until the specified condition is met. I believe that I have all of code written for Matlab, except for the command that the iteration should repeat infinitely times until the condition is met (denoted below).
Would someone be able to tell me how to translate this to Matlab syntax? I think that I should be using a while-loop, but I'm not sure since the iterations should continue until a condition is met rather than continuing while some condition is met. Is there an until equivalent? Thank you!
function xn = newton_v2(f,fd,x0,tol)
% newton iteration
xn = x0;
repeat{ %%% 'This is how I would begin the repeat command in R'
% evaluate function and derivative
fxn = feval(f,xn);
fdxn = feval(fd,xn);
% newton iteration step
xnp1 = xn - fxn/fdxn;
if(abs(xnp1 - xn)/abs(xnp1) < tol)
xn<-xnp1
end
% update
xn = xnp1;
} %%% 'This is how I would end the repeat command in R'
end
Also, please let me know if you see anything else wrong in my Matlab code.
I'm not great with R syntax, but you would have two options 1.pass in an array of values to a matlab for loop and iterate through them. Then graph it to find the best solution and try to get more precise from there 2. Set a condition on a while loop. I think you are looking more for a while loop, so you'll put your condition in there. It may be more computationally heavy, but depending on the funct. may be fine.
I do the Newton method with a while loop though the recursive version in the answer by hamaney is interesting. I do this by passing a function handle, initial guess and tolerance to a function.
function x1 = NewtonMethod(f,x,tol)
% dtol is calculated from eps based on the function handle...not shown
xi = f(x); % initial guess
dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
x1 = x - xi / dxi;
while (abs(x1 - x) < tol)
x = x1;
xi = f(x);
dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
x1 = x - xi / dxi;
end
end
There is a problem with this approach. If the initial guess is poorly conditioned or the function unbounded it is possible for this to be an infinite loop. Because of this I include a loop counter and normally break when that counter reaches a maxSteps value.
Adding the inifinite loop protection looks something like this.
xi = f(x); % initial guess
dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
x1 = x - xi / dxi;
loopCounter = 0;
while (abs(x1 - x) < tol)
x = x1;
xi = f(x);
dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
x1 = x - xi / dxi;
loopCounter = loopCounter + 1;
if loopCounter > maxSteps
% include warning message
break
end
end
Do you mean the syntax for the for loop?
If you are trying to create Newton's method, see my own implementation script
y is the function
x0 - first initial value
n - # of xns to approximate
function Xn = newtonsMethod (y,x0,n,startDomain,endDomain)
%the tangent line at any point on the curve
y1 = matlabFunction(diff(sym(y)));
Xn = x0;
x= linspace(startDomain,endDomain,1000);
%recursive call for the newton formula
for i = 1 : n
%find the tangent line
L =#(x)(y1(Xn).*(x-Xn)+y(Xn));
%find the root
Xn = Xn - (y(Xn)./y1(Xn));
end
end
This might be not the best way to do it. but it could help!

Trying to solve Simultaneous equations in matlab, cannot work out how to format the functions

I was given a piece of Matlab code by a lecturer recently for a way to solve simultaneous equations using the Newton-Raphson method with a jacobian matrix (I've also left in his comments). However, although he's provided me with the basic code I cannot seem to get it working no matter how hard I try. I've spent many hours trying to introduce the 'func' function but to no avail, frequently getting the message that there aren't enough inputs. Any help would be greatly appreciated, especially with how to write the 'func' function.
function root = newtonRaphson2(func,x,tol)
% Newton-Raphson method of finding a root of simultaneous
% equations fi(x1,x2,...,xn) = 0, i = 1,2,...,n.
% USAGE: root = newtonRaphson2(func,x,tol)
% INPUT:
% func = handle of function that returns[f1,f2,...,fn].
% x = starting solution vector [x1,x2,...,xn].
% tol = error tolerance (default is 1.0e4*eps).
% OUTPUT:
% root = solution vector.
if size(x,1) == 1; x = x'; end % x must be column vector
for i = 1:30
[jac,f0] = jacobian(func,x);
if sqrt(dot(f0,f0)/length(x)) < tol
root = x; return
end
dx = jac\(-f0);
x = x + dx;
if sqrt(dot(dx,dx)/length(x)) < tol
root = x; return
end
end
error('Too many iterations')
function [jac,f0] = jacobian(func,x)
% Returns the Jacobian matrix and f(x).
h = 1.0e-4;
n = length(x);
jac = zeros(n);
f0 = feval(func,x);
for i =1:n
temp = x(i);
x(i) = temp + h;
f1 = feval(func,x);
x(i) = temp;
jac(:,i) = (f1 - f0)/h;
end
The simultaneous equations to be solved are:
sin(x)+y^2+ln(z)-7=0
3x+2^y-z^3+1=0
x+y+Z-=0
with the starting point (1,1,1).
However, these are arbitrary and can be replaced with anything, I mainly just need to know the general format.
Many thanks, I know this may be a very simple task but I've only recently started teaching myself Matlab.
You need to create a new file called myfunc.m (or whatever name you like) which takes a single input parameter - a column vector x - and returns a single output vector - a column vector y such that y = f(x).
For example,
function y = myfunc(x)
y = zeros(3, 1);
y(1) = sin(x(1)) + x(2)^2 + log(x(3)) - 7;
y(2) = 3*x(1) + 2^x(2) - x(3)^3 + 1;
y(3) = x(1) + x(2) + x(3);
end
You can then refer to this function as #myfunc as in
>> newtonRaphson2(#myfunc, [1;1;1], 1e-6);
The reason for the special notation is that Matlab allows you to call a function with no parameters by omitting the parens () that follow it. So for example, Matlab interprets myfunc as you calling the function with no arguments (so it tries to replace it with its result) whereas #myfunc refers to the function itself, rather than its result.
Alternatively you can write a function directly using the # notation, as in
>> newtonRaphson2(#(x) exp(x) - 3*x, 2, 1e-2)
ans =
1.5315
>> newtonRaphson2(#(x) exp(x) - 3*x, 1, 1e-2)
ans =
0.6190
which are the two roots of the equation exp(x) - 3 * x = 0.
Edit - as an aside, your professor has terrible coding style (if the code in your question is a direct copy-paste of what he gave you, and you haven't mangled it along the way). It would be better to write the code like this, with indentation making it clear what the structure of the code is.
function root = newtonRaphson2(func, x, tol)
% Newton-Raphson method of finding a root of simultaneous
% equations fi(x1,x2,...,xn) = 0, i = 1,2,...,n.
%
% USAGE: root = newtonRaphson2(func,x,tol)
%
% INPUT:
% func = handle of function that returns[f1,f2,...,fn].
% x = starting solution vector [x1,x2,...,xn].
% tol = error tolerance (default is 1.0e4*eps).
%
% OUTPUT:
% root = solution vector.
if size(x, 1) == 1; % x must be column vector
x = x';
end
for i = 1:30
[jac, f0] = jacobian(func, x);
if sqrt(dot(f0, f0) / length(x)) < tol
root = x; return
end
dx = jac \ (-f0);
x = x + dx;
if sqrt(dot(dx, dx) / length(x)) < tol
root = x; return
end
end
error('Too many iterations')
end
function [jac, f0] = jacobian(func,x)
% Returns the Jacobian matrix and f(x).
h = 1.0e-4;
n = length(x);
jac = zeros(n);
f0 = feval(func,x);
for i = 1:n
temp = x(i);
x(i) = temp + h;
f1 = feval(func,x);
x(i) = temp;
jac(:,i) = (f1 - f0)/h;
end
end