Solving a system of 5 nonlinear equations in Matlab - matlab

I'm having difficulty using the fsolve function to solve a set of 5 equations in Matlab.
Here are the 5 equations:
y = a + d + e
y + x = c + d + 2e
2x = 4a + 2b + 2c
k1 = (d * b^3 / (a * c) ) * ((P/Pref)/(a+b+c+d+e))^2
k2 = be/(dc)
y,x,k1,k2,P,Pref are all parameters that I set, but would like to leave them in the function so that I can change them quickly in my code to find new answers. a,b,c,d,e are the variables that I'd like to solve for (they are compositions of a reaction equilibrium equation)
I tried to hard code the parameters in the function, but that didn't work. I'm just not sure what to do. Every thing I change creates a new error. The most common is that the data type has to be "double".
Edit: adding code
first the function:
function F = myfun(Q,I)
a = Q(1);
b = Q(2);
c = Q(3);
d = Q(4);
e = Q(5);
x = I(1);
y = I(2);
k1 = I(3);
k2 = I(4);
P = I(5);
Pref = I(6);
F(1) = a + d + e - y;
F(2) = c + d + 2*e - y - x;
F(3) = 4*a + 2*b + 2*c - 2*x;
F(4) = ((d * b^3)/(a*c))*((P/Pref)/(a+b+c+d+e))^2 - k1;
F(5) = (b*e)/(c*d);
next is the program:
%Q = [a,b,c,d,e]
%I = [x,y,k1,k2,P,Pref]
%The values for the inputs will be changed to vary the output
%Inputs:
x=5;
y=1;
k1=5;
Pref=1;
P=1;
k2=-0.01;
syms K
k1 = solve(log10(k1) - k1);
syms L
k2 = solve(log10(k2) - k2);
x = double(x);
y = double(y);
Pref = double(Pref);
P = double(P);
k1 = double(k1);
k2 = double(k2);
%Solving:
I = [x,y,k1,k2,P,Pref];
q = [0,0,0,0,0]; %initial guess
Q = fsolve(#myfun,[q,I])
when I run this, these errors comes up:
Error using myfun (line 7)
Not enough input arguments.
Error in fsolve (line 218)
fuser = feval(funfcn{3},x,varargin{:});
Error in Coal (line 27)
Q = fsolve(#myfun,[q,I])
Caused by:
Failure in initial user-supplied objective function evaluation. FSOLVE cannot continue.
Edit 2: changed the fsolve line, but still got errors:
Error using trustnleqn (line 28)
Objective function is returning undefined values at initial point. FSOLVE cannot continue.
Error in fsolve (line 376)
[x,FVAL,JACOB,EXITFLAG,OUTPUT,msgData]=...
Error in Coal (line 27)
fsolve(#(q) myfun(q,I),q)
Edit3: changed a couple parameters and the initial guess, I am now getting an answer, but it also comes up with this:
Solver stopped prematurely.
fsolve stopped because it exceeded the function evaluation limit,
options.MaxFunEvals = 500 (the default value).
ans =
0.0000 2.2174 3.7473 1.4401 3.8845
how can I get it to not stop prematurely?

Re: how can I get it to not stop prematurely?
Pass non-default options in your call to fsolve.
Refer to the signature, fsolve(myfun,q,options) here,
http://www.mathworks.com/help/optim/ug/fsolve.html
And read about creating the options using optimoptions here,
http://www.mathworks.com/help/optim/ug/optimoptions.html
You should be able to get it to "not stop prematurely" by increasing the values of convergence criteria such as TolFun and TolX.
However, it's advisable to read up on the underlying algorithms you're relying upon to perform this numerical solution here,
(EDIT: I tried to fix non-linky links, but I'm not allowed to provide more than two ... Boo) www.mathworks.com/help/optim/ug/fsolve.html#moreabout
The error you received simply indicates that after 500 function evaluations the algorithm has not yet converged on an acceptable solution conforming to the default solver options. Just increasing MaxFunEvals may allow the algorithm extra iterations needed to converge within default tolerances. For example,
options = optimoptions('MaxFunEvals',1000); % try something bigger than 500
fsolve(#(q) myfun(q,I),q,options);

Related

Using Adams-Bashforth method in Matlab to solve Lorenz-System Equation

I am trying to use my second order Adams-Bashforth function here:
function [t,x] = Adams(f,t_max,x0,N)
h = t_max/N;
t = linspace(0,t_max,N+1);
x = zeros(2,N+1);
x(:,1) = x0;
x(:,2) = x0 + h.*(f(t(1),x(:,1)));
for i=2:N
x(:,i+1) = x(:,i) + h.*((3/2.*f(t(i),x(:,i))-(1/2).*f(t(i-1),x(:,i-1))));
end
end
In order to solve the Lorenz System Equation. However, whenever I try to call the function, I get an error.
sigma = 10;
beta = 8/3;
rho = 28;
f = #(t,a) [-sigma*a(1) + sigma*a(2); rho*a(1) - a(2) - a(1)*a(3); -beta*a(3) + a(1)*a(2)];
[t,a] = Adams(f,10,[1 1 1],100);
plot3(a(:,1),a(:,2),a(:,3))
Output:
"Unable to perform assignment because
the size of the left side is 2-by-1 and
the size of the right side is 1-by-3.
Error in Project>Adams (line 55)
x(:,1) = x0;"
Is the issue with my function, or with how I am calling my function? Any help would be appreciated.
in line 5 of your Adams function: x(:,1) = x0;
the input x0 is the initial conditions [1 1 1] a row vector of size [3x1], but x is an array of size zeros(2,N+1), or [2x101].
There are several mistakes here, the first you assign a row vector to a colon vector, not only that, but the size of the container in that first column of array x which is [2x1] , that is a different size than the size of x0. that is what the error tells you.
The function is buggy there , and it wont work unless you debug it according to the original intent of that method you are trying to implement.
note that also in the script f=#(t,... is expected to have an input t, but there is not t in the expression [-sigma*a(1) + sigma*a(2); rho*a(1) - a(2) - a(1)*a(3); -beta*a(3) + a(1)*a(2)];

Problem with separating Real and Imaginary parts for fmincon (constrained MATLAB optimization). How to program it correctly?

I am trying to solve this optimization problem with fmincon function in MATLAB:
Where all H are complex matrices, g and Pdes are complex column vectors, D0 and E0 are numbers.
I expect to get complex column vector of g (and in general its should be complex), So I divided problem in two parts: real and imag, but it does not work, MATLAB returning me a message:
Not enough input arguments.
Error in temp>nonlincon (line 17)
c(1) = norm ( H_d*([g(1)+1i*g(4); g(2)+1i*g(5); g(3)+1i*g(6)]) )^2 - D_0;
Error in temp (line 12)
= fmincon(objective,x0,[],[],[],[],[],[],nonlincon);
Where I am wrong?
And in general am I right in writing given problem in the following way:?
% For example:
D_0 = 2*10^(-5)*10^(60/10);
E_0 = 50;
H_b = rand(15,3) + 1i*rand(15,3);
P_des = rand(15,1) + 1i*rand(15,1);
H_d = rand(10,3) + 1i*rand(10,3);
objective = #(g) (norm ( H_b*([g(1)+1i*g(4); g(2)+1i*g(5); g(3)+1i*g(6)]) - P_des ))^2;
x0 = ones(1,3*2)';
options = optimoptions('fmincon','MaxFunctionEvaluations',10e3);
[X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN]...
= fmincon(objective,x0,[],[],[],[],[],[],nonlincon);
% So I expect to get a column vector g: 1st 3 elements - Real part, next 3 - Imag
function [c,ceq] = nonlincon(g, H_d, E_0, D_0)
c(1) = (norm ( H_d*([g(1)+1i*g(4); g(2)+1i*g(5); g(3)+1i*g(6)]) ))^2 - D_0;
c(2) = (norm ([g(1)+1i*g(4); g(2)+1i*g(5); g(3)+1i*g(6)]))^2 - E_0;
ceq = [];
end
You just need to specify that nonlincon is a function of variable g only when calling fmincon
The code is as follow
[X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN]...
= fmincon(objective,x0,[],[],[],[],[],[],#(g)nonlincon(g, H_d, E_0, D_0));
Solution X
X = [0.2982; 0.1427; 0.3597; -0.0729; -0.1187; 0.2090]

Finding real roots of polynomial by using fzero

I want to find only real roots of the equation which is ;
4*sqrt((1-(z^2/f1^2))*(1-z^2))-(2-z^2)^2-(m*z^4*sqrt(1-z^2/f1^2)/ ...
sqrt(1-((z^2/f1^2)/y^2)))
I know that equation includes complex roots, but I do not want to see them. Moreover, my code fails and says that;
Error using fzero (line 242) Function values at interval endpoints
must be finite and real.
Error in scholte (line 21) x=fzero(fun,x0)
Here is my code;
rho2 = 1000; %kg/m3
rho1 = 2700; %kg/m3
cl2 = 1481; %m/s
cl1 = 5919; %m/s
m = rho2/rho1;
y = cl2/cl1;
poi = 0.25;
f1 = (sqrt((1-2*poi)/(2*(1-poi))))^-1;
fun = #(z) 4*sqrt((1-(z^2/f1^2))*(1-z^2))-(2-z^2)^2- ...
(m*z^4*sqrt(1-z^2/f1^2)/sqrt(1-((z^2/f1^2)/y^2)));
x0 = [1 10];
x = fzero(fun, x0)
I changed x0 interval many times, but it showed the same error. How can I fix my code?
Your problem, as Matlab tells you, is that Function values at interval endpoints must be finite and real, and in your case they are not real:
fun(x0(1))
ans =
-1.0000 + 0.1454i
Your function is probably just too complex for fzero to handle. However I am not an expert, lets see if someone with more knowledge than me can point you in the correct direction for solving that equation.

Matlab: fmincon throws error

I am implementing the expression given in the image which is the log-likelihood for AR(p) model.
In this case, p=2. I am using fmincon as the optimization tool. I checked the documentation and other examples over internet regarding the syntax of this command. Still, I am unable to mitigate the problem. Can somebody please help in eliminating the problem?
The following is the error
Warning: Options LargeScale = 'off' and Algorithm = 'trust-region-reflective' conflict.
Ignoring Algorithm and running active-set algorithm. To run trust-region-reflective, set
LargeScale = 'on'. To run active-set without this warning, use Algorithm = 'active-set'.
> In fmincon at 456
In MLE_AR2 at 20
Error using ll_AR2 (line 6)
Not enough input arguments.
Error in fmincon (line 601)
initVals.f = feval(funfcn{3},X,varargin{:});
Error in MLE_AR2 (line 20)
[theta_hat,likelihood] =
fmincon(#ll_AR2,theta0,[],[],[],[],low_theta,up_theta,[],opts);
Caused by:
Failure in initial user-supplied objective function evaluation. FMINCON cannot
continue.
The vector of unknown parameters,
theta_hat = [c, theta0, theta1, theta2] where c = intercept in the original model which is zero ; theta0 = phi1 = 0.195 ; theta1 = -0.95; theta2 = variance of the noise sigma2_epsilon.
The CODE:
clc
clear all
global ERS
var_eps = 1;
epsilon = sqrt(var_eps)*randn(5000,1); % Gaussian signal exciting the AR model
theta0 = ones(4,1); %Initial values of the parameters
low_theta = zeros(4,1); %Lower bound of the parameters
up_theta = 100*ones(4,1); %upper bound of the parameters
opts=optimset('DerivativeCheck','off','Display','off','TolX',1e-6,'TolFun',1e-6,...
'Diagnostics','off','MaxIter', 200, 'LargeScale','off');
ERS(1) = 0.0;
ERS(2) = 0.0;
for t= 3:5000
ERS(t)= 0.1950*ERS(t-1) -0.9500*ERS(t-2)+ epsilon(t); %AR(2) model y
end
[theta_hat,likelihood,exit1] = fmincon(#ll_AR2,theta0,[],[],[],[],low_theta,up_theta,[],opts);
exit(1,1)=exit1;
format long;disp(num2str([theta_hat],5))
function L = ll_AR2(theta,Y)
rho0 = theta(1); %c
rho1 = theta(2); %phi1
rho2 = theta(3); %phi2
sigma2_epsilon = theta(4);
T= size(Y,1);
p=2;
mu_p = rho0./(1-rho1-rho2); %mean of Y for the first p samples
%changed sign of the log likelihood expression
cov_p = xcov(Y);
L1 = (Y(3:end) - rho0 - rho1.*Y(1:end-1) - rho2.*Y(1:end-2)).^2;
L = (p/2).*(log(2*pi)) + (p/2).*log(sigma2_epsilon) - 0.5*log(det(inv(cov_p))) + 0.5*(sigma2_epsilon^-1).*(Y(p) - mu_p)'.*inv(cov_p).*(Y(p) - mu_p)+...
(T-p).*0.5*log(2*pi) + 0.5*(T-p).*log(sigma2_epsilon) + 0.5*(sigma2_epsilon^-1).*L1;
L = sum(L);
end
You are trying to pass constant parameters to the objective function (Y) in addition to the optimization variables (theta).
The right way of doing so is using anonymous function:
Y = ...; %// define your parameter here
fmincon( #(theta) ll_AR2(theta, Y), theta0, [],[],[],[],low_theta,up_theta,[],opts);
Now the objective function, as far as fmincon concerns, depends only on theta.
For more information you can read about anonymous functions and passing const parameters.

Using fsolve to solve Differential Equation with Varying Parameters

I am using the following code to produce a numerical solution to a system of ODE's with 6 boundary conditions.
I am using the initial conditions to obtain a solution but I must vary three other conditions in order to find the true solution. The function I have is as follows:
function diff = prob5diff(M,Fx,Fy)
u0 = [pi/2 0 0]';
sSpan = [0 13];
p = #(t,u) prob5(t,u,M,Fx,Fy);
options = odeset('reltol',1e-6,'abstol',1e-6);
[s,u] = ode45(p,sSpan,u0,options);
L = length(s);
x = u(:,2); y = u(:,3); theta = u(:,1);
diff(1) = x(L) - 5;
diff(2) = y(L);
diff(3) = theta(L) + pi/2;
end
Ultimately, different values of M,Fx, and Fy will produce different solutions and I would like a solution such that the values in diff are as close to zero as possible so I want fsolve to iterate through different values of M,Fx, and Fy
I am receiving the following error: when I call it in this way:
opt = optimset('Display','iter','TolFun',1e-6);
guess = [1;1;1];
soln = fsolve(#prob5diff,guess,opt);
Error in line:
soln = fsolve(#prob5diff,guess,opt);
Caused by:
Failure in initial user-supplied objective function evaluation. FSOLVE cannot continue.
Thanks!
One problem is that you have to call fsolve on prob5diff which takes a single vector input since your guess is a single vector:
prob5diff(x)
M = x(1);
Fx = x(2);
Fy = x(3);