Plotting parameterized solutions in matlab - matlab

I need to plot parameterized solutions for the following systems of equations using t values from 0 to 0.3 incremented by 0.001 each time:
x′  =  12.3 x  −  2.7 y
y′  =  5.7 x  −  3.7 y
This is what I have so far, but I'm pretty sure my parametric curves are wrong. I'd be expecting some exponential looking thing, not a lot of straight lines. What am I doing wrong?
A = [ 12.3, -2.7; 5.7, -3.7 ]; %initial matrix
[P D] = eig(A); %finding eigenvalues and eigenvectors
i = [1;4.3]; %initial conditions
H = inv(P)*i; %solving for c1 and c2
t = 0:0.001:0.3;
c1 = 0.2580; %constant
c2 = 4.2761; %constant
B1 = [0.9346;0.3558]; %eigenvector
B2 = [0.1775;0.9841]; %eigenvector
a = 11.2721; %eigenvalue
b = -2.6721; %eigenvalue
x1 = c1*B1*exp(a*t) + c2*B1*exp(b.*t);
x2 = c1*B2*exp(a*t) + c2*B2*exp(b.*t);
plot(x1,x2);

Your problem was calculating x1 and x2. Since B1 and B2 are vectors, doing this:
x1 = c1*B1*exp(a*t) + c2*B1*exp(b.*t);
x2 = c1*B2*exp(a*t) + c2*B2*exp(b.*t);
made x1 and x2 2 by 301 matrices.
The correct result is simpler:
x = c1*B1*exp(a*t) + c2*B2*exp(b*t);
and plotting it gives:
plot(x(1,:),x(2,:));

Related

Solving a 4 ODE system in MATLAB using ode45

I am not very used to MATLAB and I'm trying to solve the following problem using MATLAB ode45, however, it's not working.
I was working on a problem in reaction engineering, using a Semi-Batch Reactor.
The reaction is given by
A + B ---> C + D
A is placed in the reactor and B is being continuously added into the reactor with a flowrate of v0 = 0.05 L/s. Initial volume is V0 = 5 L. The reaction is elementary. The reaction constant is k = 2.2 L/mol.s.
Initial Concentrations: for A: 0.05 M, for B: 0.025 M.
Performing a mole balance of each species in the reactor, I got the following 4 ODEs, and the expression of V (volume of the reactor is constantly increasing)
Solving this system and plotting the solution against time, I should get this
Note that plots of C(C) and C(D) are the same.
And let's set tau = v0/V.
Now for the MATLAB code part.
I have searched extensively online, and from what I've learned, I came up with the following code.
First, I wrote the code for the ODE system
function f = ODEsystem(t, y, tau, ra, y0)
f = zeros(4, 1);
f(1) = ra - tau*y(1);
f(2) = ra + tau*(y0(2) - y(2));
f(3) = -ra - tau*y(3);
f(4) = -ra - tau*y(4);
end
Then, in the command window,
t = [0:0.01:5];
v0 = 0.05;
V0 = 5;
k = 2.2;
V = V0 + v0*t;
tau = v0./V;
syms y(t);
ra = -k*y(1)*y(2);
y0 = [0.05 0.025 0 0];
[t, y] = ode45(#ODEsystem(t, y, tau, ra, y0), t, y0);
plot(t, y);
However, I get this...
Please if anyone could help me fix my code. This is really annoying :)
ra should not be passed as parameter but be computed inside the ODE system. V is likewise not a constant. Symbolic expressions should be used for formula transformations, not for numerical methods. One would also have to explicitly evaluate the symbolic expression at the wanted numerical values.
function f = ODEsystem(t, y, k, v0, V0, cB0)
f = zeros(4, 1);
ra = -k*y(1)*y(2);
tau = v0/(V0+t*v0);
f(1) = ra - tau*y(1);
f(2) = ra + tau*(cB0 - y(2));
f(3) = -ra - tau*y(3);
f(4) = -ra - tau*y(4);
end
Then use the time span of the graphic, start with all concentrations zero except for A, use the concentration B only for the inflow.
t = [0:1:500];
v0 = 0.05;
V0 = 5;
k = 2.2;
cB0 = 0.025;
y0 = [0.05 0 0 0];
[t, y] = ode45(#(t,y) ODEsystem(t, y, k, v0, V0, cB0), t, y0);
plot(t, y);
and get a good reproduction of the reference image

Equating symbolic coefficients

I would like to seek y particular of ODE y'' - y' - 2y = 4x^2
I made the following script:
syms x A0 A1 A2
ypa = A2*x^2+A1*x+A0; % y_p assume
cyp = diff(ypa,2) - diff(ypa) - 2*ypa % according to ODE
P1 = 4*x^2; P2 = cyp ; % Equating P1 and P2
C = coeffs(P1 - P2,x);
A0 = solve(C(1),A0)
A1 = solve(C(2),A1)
A2 = solve(C(3),A2)
I got the correct answer for A2 = -2. But I did not get for A0 (should be -3) and A1 (should be 2). How to get them automatically?
P.S I'm using MATLAB R2013a.
Instead of calling solve 3 times, once on each equation of C, you should call it once on the entire system of equations so that the proper substitutions are done to give you a numeric result for each variable:
>> [A0, A1, A2] = solve(C)
A0 =
-3
A1 =
2
A2 =
-2

The Fastest Method of Solving System of Non-linear Equations in MATLAB

Assume we have three equations:
eq1 = x1 + (x1 - x2) * t - X == 0;
eq2 = z1 + (z1 - z2) * t - Z == 0;
eq3 = ((X-x1)/a)^2 + ((Z-z1)/b)^2 - 1 == 0;
while six of known variables are:
a = 42 ;
b = 12 ;
x1 = 316190;
z1 = 234070;
x2 = 316190;
z2 = 234070;
So we are looking for three unknown variables that are:
X , Z and t
I wrote two method to solve it. But, since I need to run these code for 5.7 million data, it become really slow.
Method one (using "solve"):
tic
S = solve( eq1 , eq2 , eq3 , X , Z , t ,...
'ReturnConditions', true, 'Real', true);
toc
X = double(S.X(1))
Z = double(S.Z(1))
t = double(S.t(1))
results of method one:
X = 316190;
Z = 234060;
t = -2.9280;
Elapsed time is 0.770429 seconds.
Method two (using "fsolve"):
coeffs = [a,b,x1,x2,z1,z2]; % Known parameters
x0 = [ x2 ; z2 ; 1 ].'; % Initial values for iterations
f_d = #(x0) myfunc(x0,coeffs); % f_d considers x0 as variables
options = optimoptions('fsolve','Display','none');
tic
M = fsolve(f_d,x0,options);
toc
results of method two:
X = 316190; % X = M(1)
Z = 234060; % Z = M(2)
t = -2.9280; % t = M(3)
Elapsed time is 0.014 seconds.
Although, the second method is faster, but it still needs to be improved. Please let me know if you have a better solution for that. Thanks
* extra information:
if you are interested to know what those 3 equations are, the first two are equations of a line in 2D and the third equation is an ellipse equation. I need to find the intersection of the line with the ellipse. Obviously, we have two points as result. But, let's forget about the second answer for simplicity.
My suggestion it's to use the second approce,which it's the recommended by matlab for nonlinear equation system.
Declare a M-function
function Y=mysistem(X)
%X(1) = X
%X(2) = t
%X(3) = Z
a = 42 ;
b = 12 ;
x1 = 316190;
z1 = 234070;
x2 = 316190;
z2 = 234070;
Y(1,1) = x1 + (x1 - x2) * X(2) - X(1);
Y(2,1) = z1 + (z1 - z2) * X(2) - X(3);
Y(3,1) = ((X-x1)/a)^2 + ((Z-z1)/b)^2 - 1;
end
Then for solving use
x0 = [ x2 , z2 , 1 ];
M = fsolve(#mysistem,x0,options);
If you may want to reduce the default precision by changing StepTolerance (default 1e-6).
Also for more increare you may want to use the jacobian matrix for greater efficencies.
For more reference take a look in official documentation:
fsolve Nonlinear Equations with Analytic Jacobian
Basically giving the solver the Jacobian matrix of the system(and special options) you can increase method efficency.

Computing CCA through three approaches

I have recently studied the concepts of CCA and wanted to implement it in MATLAB. However there is an existing matlab command canoncorr present. I wanted to write my own code. I have studied it extensively and found three approaches :
1: Hardoon : The approach uses lagrange multipliers to decompose the problem into an generalised eigenvalue problem. The code can be found here : cca_hardoon
For sanity sake I am also giving the code here : The data has to be centered previously.
function [Wx, Wy, r] = cca(X,Y)
% CCA calculate canonical correlations
%
% [Wx Wy r] = cca(X,Y) where Wx and Wy contains the canonical correlation
% vectors as columns and r is a vector with corresponding canonical
% correlations.
%
% Update 31/01/05 added bug handling.
if (nargin ~= 2)
disp('Inocorrect number of inputs');
help cca;
Wx = 0; Wy = 0; r = 0;
return;
end
% calculating the covariance matrices
z = [X; Y];
C = cov(z.');
sx = size(X,1);
sy = size(Y,1);
Cxx = C(1:sx, 1:sx) + 10^(-8)*eye(sx);
Cxy = C(1:sx, sx+1:sx+sy);
Cyx = Cxy';
Cyy = C(sx+1:sx+sy,sx+1:sx+sy) + 10^(-8)*eye(sy);
%calculating the Wx cca matrix
Rx = chol(Cxx);
invRx = inv(Rx);
Z = invRx'*Cxy*(Cyy\Cyx)*invRx;
Z = 0.5*(Z' + Z); % making sure that Z is a symmetric matrix
[Wx,r] = eig(Z); % basis in h (X)
r = sqrt(real(r)); % as the original r we get is lamda^2
Wx = invRx * Wx; % actual Wx values
% calculating Wy
Wy = (Cyy\Cyx) * Wx;
% by dividing it by lamda
Wy = Wy./repmat(diag(r)',sy,1);
2. MATLAB approach Please note the centering of data is done within the code itself.
3. CCA by Normal SVD only : This approach does not require the qr decomposition and utilizes the svd decomposition only. I have referred top this article here : cca by svd. Please refer to the text articles below which are taken from the referred article.
I have tried to code this program myself but unsuccessfully.
function [A,B,r,U,V] = cca_by_svd(x,y)
% computing the means
N = size(x,1); mu_x = mean(x,1); mu_y = mean(y,1);
% substracting the means
x = x - repmat(mu_x,N,1); y = y - repmat(mu_y,N,1);
x = x.'; y = y.';
% computing the covariance matrices
Cxx = (1/N)*x*(x.'); Cyy = (1/N)*y*(y.'); Cxy = (1/N)*x*(y.');
%dimension
m = min(rank(x),rank(y));
%m = min(size(x,1),size(y,1));
% computing the quare root inverse of the matrix
[V,D]=eig(Cxx); d = diag(D);
% Making all the eigen values positive
d = (d+abs(d))/2; d2 = 1./sqrt(d); d2(d==0)=0; Cxx_iv=V*diag(d2)*inv(V);
% computing the quare root inverse of the matrix
[V,D]=eig(Cyy); d = diag(D);
% Making all the eigen values positive
d = (d+abs(d))/2; d2 = 1./sqrt(d); d2(d==0)=0; Cyy_iv=V*diag(d2)*inv(V);
Omega = Cxx_iv*Cxy*Cyy_iv;
[C,Sigma,D] = svd(Omega);
A = Cxx_iv*C; A = A(:,1:m);
B = Cyy_iv*D.'; B = B(:,1:m);
A = real(A); B = real(B);
U = A.'*x; V = B.'*y;
r = Sigma(1:m,1:m);
I am running this code snippet:
clc;clear all;close all;
load carbig;
X = [Displacement Horsepower Weight Acceleration MPG];
nans = sum(isnan(X),2) > 0;
x = X(~nans,1:3);
y = X(~nans,4:5);
[A1, B1, r1, U1, V1] = canoncorr(x, y);
[A2, B2, r2, U2, V2] = cca_by_svd(x, y);
[A3, B3, r3] = cca(x.',y.',1);
The projection vector is coming out to be this :
>> A1
A1 =
0.0025 0.0048
0.0202 0.0409
-0.0000 -0.0027
>> A2
A2 =
0.0025 0.0048
0.0202 0.0410
-0.0000 -0.0027
>> A3
A3 =
-0.0302 -0.0050 -0.0022
0.0385 -0.0420 -0.0176
0.0020 0.0027 -0.0001
>> B1
B1 =
-0.1666 -0.3637
-0.0916 0.1078
>> B2
B2 =
-0.1668 -0.3642
-0.0917 0.1079
>> B3
B3 =
0.0000 + 0.0000i 0.3460 + 0.0000i 0.1336 + 0.0000i
0.0000 + 0.0000i -0.0967 + 0.0000i 0.0989 + 0.0000i
Question: Can someone please tell me where I am going wrong. The three approaches that I have referred all solve the same problem and ideally their solutions should converge. I admit my code 'cca_by_svd' may be wrong but hardoon's code and matlab's output should be same. Please point out to me where I am going wrong. edit I have rechecked and corrected my code. Now for this dataset the method 2 and 3 converge.
There's a few things that cca(X,Y) doesn't do that canoncorr does:
One is normalizing the data. If you add X = normc(X')' (also for Y) to your cca(X,Y) function, the output r will match that of canoncorr. If you look into canoncorr's code, you'll see that it starts by QR decomposition of X and Y.
Another difference is that eig sorts the eigenvalues in ascending order, so cca(X,Y) should flip the output of eig(Z).
NOTE: Despite correcting these differences, I wasn't able to fully recover Wx and Wy to match the outputs of canoncorr. Ideally, Wx'*Wx should look exactly alike between cca and canoncorr.

Vectorizing in matlab

I am searching for a way to get rid of the following loop (over theta):
for i=1:1:length(theta)
V2_ = kV2*cos(theta(i));
X = X0+V2_;
Y = Y0-V2_*(k1-k2);
Z = sqrt(X.^2-Z0-4*V2_.*(k.^2*D1+k1));
pktheta(:,i)=exp(-t/2*V2_).*(cosh(t/2*Z)+...
Y./((k1+k2)*Z).*sinh(t/2*Z));
end
where X0,Y0,Z0 and kV2 are dependent on the vector k (same size). t, D1, k1 and k2 are numbers. Since I have to go through this loop several times, how can I speed it up?
Thanks
Try this -
N = numel(theta);
V2_ = kV2*cos(theta(1:N));
X0 = repmat(X0,[1 N]);
Y0 = repmat(Y0,[1 N]);
Z0 = repmat(Z0,[1 N]);
X = X0 + V2_;
Y = Y0-V2_*(k1-k2);
Z = sqrt(X.^2-Z0-4.*V2_ .* repmat(((1:N).^2)*D1 + k1.*ones(1,N),[size(X0,1) 1]));
pktheta = exp(-t/2*V2_).*(cosh(t/2*Z) + Y./((k1+k2)*Z).*sinh(t/2*Z));
Definitely BSXFUN must be faster, if someone could post with it.