I want to make a code for a model of competing three species with diffusion to get plots ( 2d plot u, v, w against time ) My model is
u'=d1u_xx+(r1-a1u-b1v-c1w)u
v'=d2v_xx+(r2-a2u-b2v-c2w)v
w'=d3w_xx+(r3-a3u-b3v-c3w)w
where d1=d2=d3=1;
r1=1.5; r2=2.65; r3=3.45;
a1=0.1; b1=0.3; c1=0.01; b2=0.2;
a2=0.3; c2=0.2; c3=0.2; a3=0.01; b3=0.1.
I did the code for this model without diffusion as follow
% Define diff. equations, time span and initial conditions, e.g.
tspan = [0 20];
y0 = [0.2 0.2 0.2];
r1=1.5; r2=2.65; r3=3.45;
a1=0.1; a2=0.3; a3=0.01;
b1=0.3; b2=0.2; b3=0.1;
c1=0.01; c2=0.2; c3=0.2;
dy = #(t,y) [
(r1-a1*y(1)-b1*y(2)-c1*y(3))*y(1);
(r2-a2*y(1)-b2*y(2)-c2*y(3))*y(2);
(r3-a3*y(1)-b3*y(2)-c3*y(3))*y(3)];
% Solve differential equations
[t,y] = ode45(dy, tspan, y0);
% Plot all species against time
figure(1)
plot(t,y)
Resulting in following figure:
how to do it with diffusion like in this paper figure 10u, v, w
Related
I am trying to solve, using MATLAB, the time dependent Harmonic oscillator equation numerically. But I have no idea how to even get started as I have never learned this method in university:
X'' + w(t)^2 X = 0
with boundary conditions X_0 = 1, X_0' = 0 and Y_0 = 0, Y'_0 = 1
ode45 is a good start point.
Basic examples :
clear;close all;clc
tspan=[0 100]; % time
x_init=[5;0]; % known initial conditions
[t,y] = ode45(#vdp1,tspan,x_init);
figure(1)
plot(t,y(:,1),'r',t,y(:,2),'b')
grid on
title('Solution with ODE45');
xlabel('Time t');
ylabel('Solution y');
legend('y_1','y_2')
f=.5
[t,y] = ode45(#(t,y) vdp2(t,y,f),tspan,x_init);
figure(2)
plot(t,y(:,1),'r',t,y(:,2),'b')
grid on
title(['Solution with ODE45 and f = ' num2str(f)]);
xlabel('Time t');
ylabel('Solution y');
legend('y_1','y_2')
support functions:
function dydt = vdp1(t,y)
%
f=.1;
dydt = [y(2); sin(2*pi*f*t)*y(1)];
function dydt = vdp2(t,y,f)
%
dydt = [y(2); sin(2*pi*f*t)*y(1)];
This: https://uk.mathworks.com/matlabcentral/fileexchange/69951-runge-kutta-fixed-step-solvers?s_tid=srchtitle_harmonic%2520oscillator_81 among other examples has example1 solving damped and driven harmonic oscillators
And another harmonic oscillator solution with ODE solver:
https://uk.mathworks.com/matlabcentral/fileexchange/83233-matlab_program_solving_odes_harmonic_oscillators?s_tid=srchtitle_harmonic%20oscillator_9
You can also solve with symbolic expressions, this is Loren's post comparing symbolic and numerical solving
https://blogs.mathworks.com/loren/2010/04/08/odes-from-symbolic-to-numeric-code/?s_tid=srchtitle_harmonic%2520oscillator_105
I find the following concise introduction to ODE solving by Cleve Moler more useful than some full year university modules.
https://blogs.mathworks.com/cleve/2016/11/14/my-favorite-ode/?s_tid=srchtitle_harmonic%2520oscillator_131
When solving oscillators in polar coordinates you may need to have a look at
https://blogs.mathworks.com/cleve/2017/11/06/three-term-recurrence-relations-and-bessel-functions/?s_tid=srchtitle_harmonic%2520oscillator_140
In point 6 there's a wonderful introduction to Bessel functions and their zeros.
I have conducted a linear SVM on a large dataset, however in order to reduce the number of dimensions I performed a PCA, than conducted the SVM on a subset of the component scores (the first 650 components which explained 99.5% of the variance). Now I want to plot the decision boundary in the original variable space using the beta weights and bias from the SVM created in PCA space. But I can't figure out how to project the bias term from the SVM into the original variable space. I've written a demo using the fisher iris data to illustrate:
clear; clc; close all
% load data
load fisheriris
inds = ~strcmp(species,'setosa');
X = meas(inds,3:4);
Y = species(inds);
mu = mean(X)
% perform the PCA
[eigenvectors, scores] = pca(X);
% train the svm
SVMModel = fitcsvm(scores,Y);
% plot the result
figure(1)
gscatter(scores(:,1),scores(:,2),Y,'rgb','osd')
title('PCA space')
% now plot the decision boundary
betas = SVMModel.Beta;
m = -betas(1)/betas(2); % my gradient
b = -SVMModel.Bias; % my y-intercept
f = #(x) m.*x + b; % my linear equation
hold on
fplot(f,'k')
hold off
axis equal
xlim([-1.5 2.5])
ylim([-2 2])
% inverse transform the PCA
Xhat = scores * eigenvectors';
Xhat = bsxfun(#plus, Xhat, mu);
% plot the result
figure(2)
hold on
gscatter(Xhat(:,1),Xhat(:,2),Y,'rgb','osd')
% and the decision boundary
betaHat = betas' * eigenvectors';
mHat = -betaHat(1)/betaHat(2);
bHat = b * eigenvectors';
bHat = bHat + mu; % I know I have to add mu somewhere...
bHat = bHat/betaHat(2);
bHat = sum(sum(bHat)); % sum to reduce the matrix to a single value
% the correct value of bHat should be 6.3962
f = #(x) mHat.*x + bHat;
fplot(f,'k')
hold off
axis equal
title('Recovered feature space')
xlim([3 7])
ylim([0 4])
Any guidance on how I'm calculating bHat incorrectly would be much appreciated.
Just in case anyone else comes across this problem, the solution is the bias term can be used to find the y-intercept, b = -SVMModel.Bias/betas(2). And the y-intercept is just another point in space [0 b] which can be recovered/unrotated by inverse transforming it through the PCA. This new point can then be used to solve the linear equation y = mx + b (i.e., b = y - mx). So the code should be:
% and the decision boundary
betaHat = betas' * eigenvectors';
mHat = -betaHat(1)/betaHat(2);
yint = b/betas(2); % y-intercept in PCA space
yintHat = [0 b] * eigenvectors'; % recover in original space
yintHat = yintHat + mu;
bHat = yintHat(2) - mHat*yintHat(1); % solve the linear equation
% the correct value of bHat is now 6.3962
I would like to plot this function of Two Variables you can find it here
$$z^2=t(t-i) \Longleftrightarrow x^2+y^2=4x^2y^2 \Longleftrightarrow y=\dfrac{\pm x}{\sqrt{4x^2-1}} \mbox{ with } |x|>\frac{1}{2}$$
would someone show me step by step how to plot this in matlab
is there any script or toolbox in http://www.mathworks.com/matlabcentral/fileexchange
which make plot of that kind of curves quickly
this is by geogebra
This is by wolframe
You can use symbolic variables with ezplot.
syms x y % makes symbolic variables
h1 = ezplot('-4*x^2*y^2+x^2+y^2'); % plots the equation
axis equal
set(h1, 'Color', 'k');
Or you can define a function,
f = #(x,y) -4.*x.^2.*y.^2+x.^2+y.^2;
h1 = ezplot(f);
set(h1, 'Color', 'k');
It won't be easy to have the axis in the middle, I hope it's not necessary to have that.
Edit
You can download oaxes here
syms x y
h1 = ezplot('-4*x^2*y^2+x^2+y^2');
axis equal
set(h1, 'Color', 'm');
oaxes('TickLength',[3 3],'Arrow','off','AxisLabelLocation','side',...
'LineWidth',1)
Edit
For 3D plot try this,
% First line provides a grid of X and Y varying over -5 to 5 with .5 as step-size
[X,Y] = meshgrid(-5:.5:5);
% instead of "=0", Z takes the values of the equation
Z = -4 .* X.^2 .* Y.^2 + X.^2 + Y.^2;
surf(X,Y,Z) % makes a 3D plot of X,Y,Z
You can also try contourf(X,Y,Z) for 2D plot.
I've got two second order non-linear differential equations which I need to solve in order to model and plot the motion of a mass hanging on a spring which is swinging like a pendulum. They are here:
I'm using odeToVectorField to rewrite them as first order linear ODEs, then I call ode45 to solve the resulting system of equations. But when I plot the results, it gives me strange answers, like negative radius, etc.
Can anyone help me find where I've messed up my code? Thanks a lot!
My code is as follows:
global m R g B k %declare global variables to use them everywhere
m=1.0; %mass of ball [kg]
k=200; % stiffness of the spring [N/m]
R=0.5; % unstretched length of the spring [m]
g=9.81; % acceleration due to the gravity [m/s^2]
B=0; % coefficient of air drag [kg/m]
syms r(t) f(t)
[V] = odeToVectorField(diff(r,2)== r*((diff(f,1))^2) + (g*cos(f))-(k*(r-R))-B*diff(r,1)*sqrt(diff(r,1)^2 +r^2*diff(f,1)^2),...
diff(f,2)== ((g*sin(f)+2*diff(r,1)*diff(f,1))/-r)-B*diff(f,1)*sqrt(diff(r,1)^2 +r^2*diff(f,1)^2));
F = matlabFunction(V,'vars',{'t','Y'});
%define initial conditions:
theta_0=(70*pi/180);
theta_dot_0=0;
r_0= R + (m*g*cos(theta_0))/k ;
r_dot_0=0;
t_start=0; %start time
t_step=.01; % time step
t_final=5; % final time
%Solve that system of ODEs from [V]
[t , X]=ode45(F, t_start:t_step:t_final , [r_0;r_dot_0;theta_0;theta_dot_0]);
figure(1)
subplot(2,1,1)
plot(t,X(:,1),'LineWidth',2)
xlabel('t');ylabel('r','fontsize',12);
hold on
subplot(2,1,2)
plot(t,X(:,2),'LineWidth',2)
xlabel('t');ylabel('r dot','fontsize',12);
hold on
figure(2)
subplot(2,1,1)
plot(t,X(:,3),'LineWidth',2)
xlabel('t');ylabel('theta [rad]','fontsize',12);
hold on
subplot(2,1,2)
plot(t,X(:,4),'LineWidth',2)
xlabel('t');ylabel('theta dot [rad/s]','fontsize',12);
hold on
Dx=y
Dy=-k*y-x^3+9.8*cos(t)
inits=('x(0)=0,y(0)=0')
these are the differential equations that I wanted to plot.
first, I tried to solve the differential equation and then plot the graph.
Dsolve('Dx=y','Dy=-k*y-x^3+9.8*cos(t)', inits)
like this, however, there was no explicit solution for this system.
now i am stuck :(
how can you plot this system without solving the equations?
First define the differential equation you want to solve. It needs to be a function that takes two arguments - the current time t and the current position x, and return a column vector. Instead of x and y, we'll use x(1) and x(2).
k = 1;
f = #(t,x) [x(2); -k * x(2) - x(1)^3 + 9.8 * cos(t)];
Define the timespan you want to solve over, and the initial condition:
tspan = [0, 10];
xinit = [0, 0];
Now solve the equation numerically using ode45:
ode45(f, tspan, xinit)
which results in this plot:
If you want to get the values of the solution at points in time, then just ask for some output arguments:
[t, y] = ode45(f, tspan, xinit);
You can plot the phase portrait x against y by doing
plot(y(:,1), y(:,2)), xlabel('x'), ylabel('y'), grid
which results in the following plot