Trying to use pdepe function to solve spherical diffusion equation - matlab

I need to solve the spherical pde diffusion equation:
dq/dt=(1/r^2)*d/dr(r^2*D*(dq/dr))
D is a constant
initial condition is q=0 at t=0
boundary conditions are: dq/dr=0 at r=0, q=1 at r=Rc
I have written the following code but I am getting an error:
function pde1
m=2;
x=linspace(0.01,1,20);
t=linspace(0.01,2,10);
sol=pdepe(m,#pdefun,#pdeic,#pdebc,x,t);
u=sol(:,:,1);
% A surface plot
surf(x,t,u)
title('Surface plot')
xlabel('Distance x')
ylabel('Time t')
end
%-----------------------------------
function [c,f,s]=pdefun(x,t,u,DuDx)
global d
c=1/d;
f=DuDx;
s=0;
end
%-----------------------------------------------------
function [pl,ql,pr,qr]= pdebc(xl,ul,xr,ur,t)
global r
pl=0;
ql=0;
pr=1;
qr=r;
end
%------------------------------------------------
function u0 = pdeic(x)
u0=0;
end
could you please tell me what's wrong with it?
The error is:
Error using /
Matrix dimensions must agree.
Error in pdefun (line 3)
c=1/d;
Error in pdepe (line 246)
[c,f,s] = feval(pde,xi(1),t(1),U,Ux,varargin{:});
Error in pde1 (line 5)
sol=pdepe(m,#pdefun,#pdeic,#pdebc,x,t);
Thanks

Related

Numerical Convolution of Two Signals in MATLAB and Plotting the Output

without using conv() command, I want to convolve two signals:
This is the code I write:
syms n k i
f= #(n) 2.*(0<=n<=9);
h(n)=((8/9)^n).*heaviside(n-3);
L = length(f);
M = length(h(n));
out=L+M-1;
y=zeros(1,out);
for i = 1:L
for k = 1:M
y(i+k-1) = y(i+k-1) + h(k)*f;
end
end
However, I get an error:
Unable to perform assignment because value of type 'sym' is not convertible to 'double'.
Error in untitled7 (line 13)
y(i+k-1) = y(i+k-1) + h(k)*f;
Caused by:
Error using symengine
Unable to prove '(0.0 <= 0.0) <= 0.0' literally. Use 'isAlways' to test the statement mathematically.
I cannot find a way to fix it and also I do not know how to plot it at the end because of this. Can you help me in both of these issues please?
example how to convolve without command conv
nstop=20;
n1=[-nstop:1:nstop];
n0=nstop+1 % n1(n0)=0
h=zeros(1,numel(n1));
x1=zeros(1,numel(n1));
h(n0+[3:nstop])=(8/9).^[3:nstop];
x1(n0+[0:9])=2;
X1=flip(hankel(x1),2)
H=repmat(h,numel(n1),1);
conv_x_h=sum(X1.*H,2)';
n2=[0:numel(n1)-1]; % time reference for resulting conv
figure;
stem(n1,x1)
hold on
stem(n1,h);
grid on
legend('x1(n)','h(n)')
figure
stem(n2,conv_x_h)
grid on
title('conv(x1,h)')

One or more output arguments not assigned

I want to implement a convex-relaxation for the E-optimality design criterion, that is:
By defining
the optimization problem would be
I have implemented in Matlab using this function
function [d] = e_optimality(Uk, s, sigma)
%% E-OPTIMALITY DESIGN CRITERION, CONVEX RELAXATION
%
% OUTPUT: sampling_set= vector with ordered sampling
% set
%
% INPUT: Uk= NxK Laplacian eigenvector in the selected band
% s= number of samples
% sigma: entry noise matrix
N= size(Uk,1);
Sigma= diag(sigma*ones(N,1))
Sigma_inv= inv(Sigma);
cvx_begin
variable d(N)
D= diag(d)
B= Uk'*Sigma_inv* D*Uk;
minimize -lambda_min(B)
subject to
d*ones(N,1)==s;
0<=d<=1;
cvx_end
Unfortunately, when launghing the function I have the following error:
One or more output arguments not assigned during call to "varargout".
Error in minimize (line 14)
x = evalin( 'caller', sprintf( '%s ', varargin{:} ) );
Error in e_optimality (line 20)
minimize -lambda_min(B)
It seems to be the minimize -lambda_min in CVX causing the problem. What could it be?
Thank you

How can MATLAB use the inputdlg function to process a symbolic function input?

I'm using MATLAB R2016b - student edition to develop an m-file which takes as input a symbolic differential equation, f(t,y), and outputs a slope field and solution curve based on an initial condition. The code is
prompt={'dy/dt =','tspan','y0 ='};
title='Slope Field Calculator';
answer=inputdlg(prompt,title);
tspan = str2num(answer{2}); %#ok<*ST2NM>
y0 = str2double(answer{3});
syms t y
f = symfun(sym(answer{1}),[t,y]);
[t,y] = ode45(f, tspan, y0);
hold on
dirfield(f,-5:.3:5,-5,.3:5)
plot(t,y,'b','LineWidth',2)
The dirfield(f,-5:.3:5,-5:.3:5) function has input f as an # function, or an inline function, or the name of an m-file with quotes. The dirfield function then plots a direction field for a first order ODE of the form y' = f(t,y) using t-values from t1 to t2 with spacing of dt and using y-values from y1 to y2 with spacing of dy.
According to MATLAB help, the ode45 function solves differential equations.
[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] then integrates the differential equation y' = f(t,y) from time T0 to TFINAL with initial conditions Y0. The input ODEFUN is a function handle. For a scalar T and a vector Y, ODEFUN(T,Y) must return a column vector corresponding to f(t,y).
When I run the code, the dialogue box runs nicely and accepts my inputs. But when I click "OK", the code throws this error:
Warning: Support of character vectors that are not valid variable names or
define a number will be removed in a
future release. To create symbolic expressions, first create symbolic
variables and then use operations on them.
> In sym>convertExpression (line 1559)
In sym>convertChar (line 1464)
In sym>tomupad (line 1216)
In sym (line 179)
In SlopeFieldsSolutionCurves (line 9)
Undefined function 'exist' for input arguments of type 'symfun'.
Error in odearguments (line 59)
if (exist(ode)==2)
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options,
varargin);
Error in SlopeFieldsSolutionCurves (line 10)
[t,y] = ode45(f, tspan, y0);
Where am I going wrong?
ode45 takes a function handle, not a symbolic function. Use matlabFunction instead:
[t,y] = ode45(matlabFunction(f), tspan, y0);
To get rid of the first warning, you need to define f a bit differently:
f = evalin( symengine, answer{1} );
f = symfun( f, [t,y] );

Stochastic Differential Equations using Euler Method in Matlab

I am trying to solve a system of two stochastic differential equations using "sde_euler". Here is my code:
function y = stoch_Fx_model(t0,tf,F0,x0)
r=1;
sig=1;
lambda=1;
h=1;
S=1;
f= #(t,Y)[r.*Y(1).*(1-Y(1)) -h.*Y(1).*(1-Y(2))./(Y(1)+S);
lambda.*Y(2).*(1-Y(2)).*(1+sig.*(2.*Y(2)-2.*Y(1)-1))];
g=#(t,Y)[0.5;0.6];
dt=0.001;
t=t0:dt:tf;
Y0=[F0;x0];
opts = sdeset('ConstGFUN','yes','NonNegative','yes');
y = sde_euler(f,g,t,Y0,opts);
y = min(y,1);
plot(t,y(:,1))
end
After specifying the values of t0,tf,x0,F0 I run the code and I am encountering the following error:
Error using sdearguments (line 22)
Input vector TSPAN must have length >= 2. See SDE_EULER.
Error in sde_euler (line 130)
[N,D,tspan,tdir,lt,y0,fout,gout,dgout,dg,h,ConstStep,dataType,NonNegative,...
Error in stoch_Fx_model (line 19)
y = sde_euler(f,g,t,Y0,opts);
I don't understand my mistake. my TSPAN is greater than 2 in length. Here is the source for the toolbox:
https://github.com/horchler/SDETools/blob/master/SDETools/sde_euler.m
Any help please?
thank you!

Convert 1x1 sym to float

I attempt to convert a 1x1 sym to float in the program below below but it fails. Why?
The culprit line:
sol = ode45(M,[30 45],[double(H0) double(V0)]);
The error message:
Error using odearguments (line 111) Inputs must be floats, namely
single or double.
Error in ode45 (line 114) [neq, tspan, ntspan, next, t0, tfinal, tdir,
y0, f0, odeArgs, odeFcn, ...
Error in extra_credit_HW5_ME70 (line 60) sol = ode45(M,[30
45],[subs(H0) subs(V0)]);
The code:
clc;
clear all;
close all;
%This program solves the rocket program by using a system of second order
%differential which I derived (see Homework 5)
%code explanation from http://www.mathworks.com/products/symbolic/code-examples.html? file=/products/demos/symbolictlbx/second_order_differential_equation/solve-a-second-order-differential-equation.html
Ve=3500;
Mo=400;
Me=5;
g=9.81;
Cd=.5;
Af=.2;
R=287
T=273.15;
Patm=101325;
syms y(t);
%Note: From the hw: "Take the density of air at sea level to be 1.21
%kg/m3." I decided to model the density with an exponential function p(h)=(Patm*exp(-g*y/(R*T))/(R*T))
V = odeToVectorField(diff(y, 2) == Ve*Me/(Mo-Me.*t)-g-.5*Cd* (Patm*exp(-g*y/(R*T))/(R*T)) *diff(y).^2*Af/(Mo-Me.*t));
M = matlabFunction(V,'vars', {'t','Y'});
sol = ode45(M,[0 30],[0 0]);
x = linspace(0,30,250);
y = deval(sol,x,1);
plot(x,y);
% legend('No air resistance, air resistance');
hold on;
Mo=350;
syms y(t);
%Initial conditions for case where mass is dumped.
H0=y(end);
V0=( (y(end)-y(end-1)) / (x(end)-x(end-1)) );
%Note: From the hw: "Take the density of air at sea level to be 1.21
%kg/m3." I decided to model the density with an exponential function p(h)=(Patm*exp(-g*y/(R*T))/(R*T))
V = odeToVectorField(diff(y, 2) == Ve*Me/(Mo-Me.*t)-g-.5*Cd* (Patm*exp(-g*y/(R*T))/(R*T)) *diff(y).^2*Af/(Mo-Me.*t));
M = matlabFunction(V,'vars', {'t','Y'});
sol = ode45(M,[30 45],[double(H0) double(V0)]);
x = linspace(30,45,500);
y = deval(sol,x,1);
plot(x,y,'cyan');
% legend('No air resistance, air resistance');
title('Rocket height versus time for stages launch')
xlabel('time (seconds)')
ylabel('height (meters)')