MATLAB : Error using fminsearch() - matlab

clc; clearvars; clear all;
syms T; syms E; syms v1; syms v2; syms v3;
assume(v1>0 & v1<50000);
assume(v2>0 & v2<50000);
assume(v3>0 & v3<60000);
b = 10/60;
fun = int(exp(-E/(8.314*T)),T,300,T);
s1 = 175.6 * 10^3;
fun11 = (1/(v1*sqrt(2*pi)))* exp(- ((E-s1)^2)/(2*v1^2));
a1 = 10^14.52;
fun12 = int(exp((-a1/b)*fun)*fun11,E,s1-3*v1,s1+3*v1);
alpha1 = 1 - fun12;
s2 = 185.4 * 10^3;
fun21 = (1/(v2*sqrt(2*pi)))* exp(- ((E-s2)^2)/(2*v2^2));
a2 = 10^13.64;
fun22 = int(exp((-a2/b)*fun)*fun21,E,s2-3*v2,s2+3*v2);
alpha2 = 1 - fun22;
s3 = 195.4 * 10^3;
fun31 = (1/(v3*sqrt(2*pi)))* exp(- ((E-s3)^2)/(2*v3^2));
a3 = 10^13.98;
fun32 = int(exp((-a3/b)*fun)*fun31,E,s3-3*v3,s3+3*v3);
alpha3 = 1 - fun32;
alpha = (alpha1 + alpha2 + alpha3)/3
alphaexp=[0.01134 0.04317];% 0.06494 0.08783 0.17053 0.32533 0.49142 0.55575 0.59242 0.6367 0.678 0.71621 0.75124 0.78442 0.81727];
T = [350 400]; %T = [350:50:1050];
minfunc = (subs(alpha)-alphaexp).^2
error1 = sum(minfunc)
error = matlabFunction(error1)
[xfinal,fval] = fminsearch(#(x)error(x(1),x(2),x(3)),[4300 3500 32000])
The above code produces an error that 'E' is an undefined function or variable. However during all the integrations (fun12, fun22 and fun 32), I have clearly indicated that the integration is over the variable E, with limits containing v1, v2 and v3 respectively. (So E should not even exist in the final error function).
Am I doing some mistake implementing the fminsearch function?
Any help will be highly appreciated.

It doesn't even reach the min search. The issue is on the integrations.
Looks like Matlab can't compute a closed form (though the error is not really descriptive).
You can reproduce your this by just doing.
error = matlabFunction(error1)
error(4300, 3500, 32000)
A slow work around is to manually substitute, then numerically compute your solution:
vpa(subs(error1,[v1,v2,v3],[4300 3500 32000]))
The bottleneck is in the substitution. I guess there is some way to combine vpa with matlabFunction to make all this faster, but I don't know about it.

Related

Problems integrating function with two variables with singularity in one point (MATLAB)

I've been trying to integrate the function given in the code over "phi" and "r". Therefor I'm using the Matlab function "integral2". The function has a singularity at (r,phi)=(1,0) (here's a picture), which lets the integrator reach the max possible function evaluations and yields and error. I guess this has not to do with the singularity itself but with the very steep descent next to it!?
I'd be happy for any suggestions on how to get the integration working!
Maybe another integrator or a substitution of variables?
Thanks a lot! :)
p = #(r) 1./sqrt(1-r.^2);
x = 1;
z = 1e-12;
nu = .3;
X = #(r,phi) x-r.*cos(phi);
Y = #(r,phi) -r.*sin(phi);
R = #(r,phi) (X(r,phi).^2 + Y(r,phi).^2).^.5;
Rho = #(r,phi) (X(r,phi).^2 + Y(r,phi).^2 + z^2).^.5;
f1 = #(r,phi) (1 - z./Rho(r,phi)).*(X(r,phi).^2 - Y(r,phi).^2)./R(r,phi).^2;
f2 = #(r,phi) f1(r,phi) + z*Y(r,phi).^2./Rho(r,phi).^3;
f3 = #(r,phi) (1 - 2*nu)./R(r,phi).^2.*f2(r,phi) - 3*z*X(r,phi).^2./Rho(r,phi).^5;
fun = #(r,phi) r.*p(r).*f3(r,phi);
sx = 1/2/pi*integral2(fun,0,1,0,pi);

Performing closed loop system response using lsim using matlab

I'm trying to replicate the step response of a certain system using the lsim function however the resulting output isn't quite right. Is there anything I'm doing wrong?
Here's a comparison of my codes:
USING STEP():
s = tf('s');
G = 56.54/(0.12*s^2+0.6*s+58.31);
D = 0.21 + 19.95/s + 0.04*s;
H = G*D/(1+G*D);
y = 2.5*step(H);
plot(y)
USING LSIM():
ya = 0;
e = 2.5;
t1 = 0:.05:10;
er = 2.5*ones(length(t1),1);
G = 56.54/(0.12*s^2+0.6*s+58.31);
D = 0.21 + 19.95/s + 0.04*s;
GDss = ss(D*G);
x = [0 0 0];
for k = 1:100
[y,t,x] = lsim(GDss,er,t1,x);
ya(k) = y(length(t1));
er = (e - y(length(t1)))*ones(length(t1),1);
x = x(98:100);
end
plot(ya)
Plots y and ya "should" be the same but it's not what's coming up.
Help?
As far as I can see, you are calculating the step response of H = G*D/(1+G*D); with "step()", but calculating the step response of GDss = D*G; with "lsim()". Since the systems are not the same, the results will not be the same either.
As Captain Future mentioned, you are not checking equivalent things. And of course because of that the open loop system is unstable and blows up.
However for such things do it a bit more structured for your own sake and also lsim already does that for loop for you.
H = minreal(feedback(series(D,G),1));
opt = stepDataOptions('StepAmplitude',2.5);
step(H,1,opt)
%
t = 0:0.01:1;
u = ones(1,length(t));
figure,lsim(H,u,t)

Solving mulitple nonlinear equations in MATLAB

Hi I am very new to MATLAB. I was trying to solve these equations to either get an analytical solution or solve them numerically. For the analytical solution, I get the following error:
Warning: Cannot solve symbolically. Returning a numeric approximation instead.
In solve (line 305)
Here is my code:
syms A B Ph Pl
delta = 0.1;
mu = 0.02;
sigma = 0.2;
w = 1;
k = 3;
l = 2;
beta = (0.5 - mu/sigma^2) + ((mu/sigma^2 - 0.5)^2 + 2*delta/sigma^2)^0.5;
alpha = -((0.5 - mu/sigma^2) - ((mu/sigma^2 - 0.5)^2 + 2*delta/sigma^2)^0.5);
eqn1 = (A*(Ph^(-alpha)) + (Ph/delta-mu)) -(B*Ph^beta)-k;
eqn2 = (A*Pl^(-alpha) + Pl/(delta-mu) -w/delta) - B*Pl^beta + l;
eqn3 = -alpha*A*(Ph^(-alpha-1)) + 1/(delta-mu) - (beta*B*Ph^(beta-1));
eqn4 = alpha*A*Pl^(-alpha-1)- (beta*B*Pl^(beta-1));
sol = solve([eqn1==0, eqn2==0, eqn3==0, eqn4==0], [A, B, Ph, Pl]);
Matlab is telling you it can't find an analytic solution, but it is definitely finding numerical solutions when I run it, however, they're all complex. Type:
sol.A
in your command window to see what A looks like, same with B, Ph and Pl.

Matlab - Unexpected Results from Differential Equation Solver Ode45

I am trying to solve a differential equation with the ode solver ode45 with MATLAB. I have tried using it with other simpler functions and let it plot the function. They all look correct, but when I plug in the function that I need to solve, it fails. The plot starts off at y(0) = 1 but starts decreasing at some point when it should have been an increasing function all the way up to its critical point.
function [xpts,soln] = diffsolver(p1x,p2x,p3x,p1rr,y0)
syms x y
yp = matlabFunction((p3x/p1x) - (p2x/p1x) * y);
[xpts,soln] = ode45(yp,[0 p1rr],y0);
p1x, p2x, and p3x are polynomials and they are passed into this diffsolver function as parameters.
p1rr here is the critical point. The function should diverge after the critical point, so i want to integrate it up to that point.
EDIT: Here is the code that I have before using diffsolver, the above function. I do pade approximation to find the polynomials p1, p2, and p3. Then i find the critical point, which is the root of p1 that is closest to the target (target is specified by user).
I check if the critical point is empty (sometimes there might not be a critical point in some functions). If its not empty, then it uses the above function to solve the differential equation. Then it plots the x- and y- points returned from the above function basically.
function error = padeapprox(m,n,j)
global f df p1 p2 p3 N target
error = 0;
size = m + n + j + 2;
A = zeros(size,size);
for i = 1:m
A((i + 1):size,i) = df(1:(size - i));
end
for i = (m + 1):(m + n + 1)
A((i - m):size,i) = f(1:(size + 1 - i + m));
end
for i = (m + n + 2):size
A(i - (m + n + 1),i) = -1;
end
if det(A) == 0
error = 1;
fprintf('Warning: Matrix is singular.\n');
end
V = -A\df(1:size);
p1 = [1];
for i = 1:m
p1 = [p1; V(i)];
end
p2 = [];
for i = (m + 1):(m + n + 1)
p2 = [p2; V(i)];
end
p3 = [];
for i = (m + n + 2):size
p3 = [p3; V(i)];
end
fx = poly2sym(f(end:-1:1));
dfx = poly2sym(df(end:-1:1));
p1x = poly2sym(p1(end:-1:1));
p2x = poly2sym(p2(end:-1:1));
p3x = poly2sym(p3(end:-1:1));
p3fullx = p1x * dfx + p2x * fx;
p3full = sym2poly(p3fullx); p3full = p3full(end:-1:1);
p1r = roots(p1(end:-1:1));
p1rr = findroots(p1r,target); % findroots eliminates unreal roots and chooses the one closest to the target
if ~isempty(p1rr)
[xpts,soln] = diffsolver(p1x,p2x,p3fullx,p1rr,f(1));
if rcond(A) >= 1e-10
plot(xpts,soln); axis([0 p1rr 0 5]); hold all
end
end
I saw some examples using another function to generate the differential equation but i've tried using the matlabFunction() method with other simpler functions and it seems like it works. Its just that when I try to solve this function, it fails. The solved values start becoming negative when they should all be positive.
I also tried using another solver, dsolve(). But it gives me an implicit solution all the time...
Does anyone have an idea why this is happening? Any advice is appreciated. Thank you!
Since your code seems to work for simpler functions, you could try to increase the accuracy options of the ode45 solver.
This can be achieved by using odeset:
options = odeset('RelTol',1e-10,'AbsTol',1e-10);
[T,Y] = ode45(#function,[tspan],[y0],options);

Fourth-order Runge–Kutta method (RK4) collapses after a few iterations

I'm trying to solve:
x' = 60*x - 0.2*x*y;
y' = 0.01*x*y - 100* y;
using the fourth-order Runge-Kutta algorithm.
Starting points: x(0) = 8000, y(0) = 300 range: [0,15]
Here's the complete function:
function [xx yy time r] = rk4_m(x,y,step)
A = 0;
B = 15;
h = step;
iteration=0;
t = tic;
xh2 = x;
yh2 = y;
rr = zeros(floor(15/step)-1,1);
xx = zeros(floor(15/step)-1,1);
yy = zeros(floor(15/step)-1,1);
AA = zeros(1, floor(15/step)-1);
while( A < B)
A = A+h;
iteration = iteration + 1;
xx(iteration) = x;
yy(iteration) = y;
AA(iteration) = A;
[x y] = rkstep(x,y,h);
for h2=0:1
[xh2 yh2] = rkstep(xh2,yh2,h/2);
end
r(iteration)=abs(y-yh2);
end
time = toc(t);
xlabel('Range');
ylabel('Value');
hold on
plot(AA,xx,'b');
plot(AA,yy,'g');
plot(AA,r,'r');
fprintf('Solution:\n');
fprintf('x: %f\n', x);
fprintf('y: %f\n', y);
fprintf('A: %f\n', A);
fprintf('Time: %f\n', time);
end
function [xnext, ynext] = rkstep(xcur, ycur, h)
kx1 = f_prim_x(xcur,ycur);
ky1 = f_prim_y(xcur,ycur);
kx2 = f_prim_x(xcur+0.5*h,ycur+0.5*h*kx1);
kx3 = f_prim_x(xcur+0.5*h,ycur+0.5*h*kx2);
kx4 = f_prim_x(xcur+h,ycur+h*kx3);
ky2 = f_prim_y(xcur+0.5*h*ky1,ycur+0.5*h);
ky3 = f_prim_y(xcur+0.5*h*ky2,ycur+0.5*h);
ky4 = f_prim_y(xcur+h*ky2,ycur+h);
xnext = xcur + (1/6)*h*(kx1 + 2*kx2 + 2*kx3 + kx4);
ynext = ycur + (1/6)*h*(ky1 + 2*ky2 + 2*ky3 + ky4);
end
function [fx] = f_prim_x(x,y)
fx = 60*x - 0.2*x*y;
end
function [fy] = f_prim_y(x,y)
fy = 0.01*x*y - 100*y;
end
And I'm running it by executing: [xx yy time] = rk4_m(8000,300,10)
The problem is that everything collapses after 2-3 iterations returning useless results. What am I doing wrong? Or is just this method not appropriate for this kind equation?
The semicolons are intentionally omitted.
Looks like I didn't pay attention to actual h size. It works now! Thanks!
Looks like some form of the Lotka-Volterra equation?
I'm not sure if if your initial condition is [300;8000] or [8000;300] (you specify it both ways above), but regardless, you have an oscillatory system that you're trying to integrate with a large fixed time step that is (much) greater than the period of oscillation. This is why your error explodes. If you try increasing n (say, 1e6), you'll find that eventually you'll get a stable solution (assuming that your Runge-Kutta implementation is otherwise correct).
Is there a reason why you're not using Matlab's builtin ODE solvers, e.g. ode45 or ode15s?
function ode45demo
[t,y]=odeode45(#f,[0 15],[300;8000]);
figure;
plot(t,y);
function ydot=f(t,y)
ydot(1,1) = 60*y(1) - 0.2*y(1)*y(2);
ydot(2,1) = 0.01*y(1)*y(2) - 100*y(2);
You'll find that adaptive step size solvers are much more efficient for these types of oscillatory problems. Because your system has such a high frequency and seems rather stiff, I suggest that you also look at what ode15s gives and/or adjust the 'AbsTol' and 'RelTol' options with odeset.
The immediate problem is that the RK4 code was not completely evolved from the scalar case to the case of two coupled equations. Note that there is no time parameter in the derivative funtions. x and y are both dependent variables and thus get the slope update defined by the derivative functions in every step. Then xcur gets the kx updates and ycur gets the ky updates.
function [xnext, ynext] = rkstep(xcur, ycur, h)
kx1 = f_prim_x(xcur,ycur);
ky1 = f_prim_y(xcur,ycur);
kx2 = f_prim_x(xcur+0.5*h*kx1,ycur+0.5*h*ky1);
ky2 = f_prim_y(xcur+0.5*h*kx1,ycur+0.5*h*ky1);
kx3 = f_prim_x(xcur+0.5*h*kx2,ycur+0.5*h*ky2);
ky3 = f_prim_y(xcur+0.5*h*kx2,ycur+0.5*h*ky2);
kx4 = f_prim_x(xcur+h*kx3,ycur+h*ky3);
ky4 = f_prim_y(xcur+h*kx3,ycur+h*ky3);
xnext = xcur + (1/6)*h*(kx1 + 2*kx2 + 2*kx3 + kx4);
ynext = ycur + (1/6)*h*(ky1 + 2*ky2 + 2*ky3 + ky4);
end