Problems with multiple functions in the same m file ( Matlab) - matlab

I am having some issues implementing multiple functions in the same m file. The following code includes three functions which are called in the function HeatTransferModel. If I set up the m file exactly like the following, it is unable to recognize the functions RadOnly,analytica and RadConv. However, if I create separate m file for RadOnly,analytica and RadConv, the code works. Do you know why? How can I integrate all these functions in one m file? Sorry about all the unnecessary information.
function HeatTransferModel
global e rho sigma c V Arad Twall Ti tend h Tinf
e = 0.87;
rho = 770; %kg/m3
sigma = 5.67E-08; %Stefan Boltzman constant
c = 1900; %Heat capacity of white oak wood
Lavg = 0.3686;
Wavg = 0.08382;
Havg = 0.05715;
V = 10*Lavg*Wavg*Havg; %Volume of the lumped wood
Arad =2*(Lavg*3*Havg) + 2*(3*Havg*3*Wavg) + Lavg*3*Wavg ; %Surface area of the lump that is exposed to radiation
Twall = 755; %Wall temperature of the furnace
Ti = 300; %Initial temperature of the wood when it is thrown in the furnace
tend = 500; %Seconds
h = 10;
Tinf = 500; %Temperature of the incoming air
[timeODE,TODE] = ode45('RadOnly',[0:1:tend],Ti);
[timeRadConv,TRadConv] = ode45('RadConv',[0,tend],Ti);
timeanalytical = analytical(TODE);
plot(timeODE,TODE,timeanalytical,TODE,timeRadConv,TRadConv);
legend('ODE Solver','Analytical Solution','RadConv');
title('Lumped Capacitance Model')
xlabel('Time [s]')
ylabel('Bulk Wood Temperature [K]')
end
function RadiationODE = RadOnly(t,T)
global e rho sigma c V Arad Twall h Tinf
RadiationODE = -e*Arad*sigma*(T^4 - Twall^4)/(rho*V*c);
end
function time = analytical(T)
global e rho sigma c V Arad Twall Ti
time = ((rho*V*c)./(4*e*Arad*sigma*Twall^3)).*( log( abs((Twall + T)./(Twall-T))) - log(abs((Twall + Ti)./(Twall-Ti))) + 2*( atan(T./Twall) - atan(Ti/Twall)));
end
function RadConvODE = RadConv(t,T)
global e rho sigma c V Arad Twall h Tinf
RadConvODE = -e*Arad*sigma*(T.^4 - Twall^4)./(rho*V*c) + (h*Arad.*(T - Tinf))./(rho*V*c);
end

You can't pass subfunction handles to Ode45, because that is in a different workspace than the primary function.

Related

Solve simultaneous differential equations with imbedded functions and a parameter estimation

The aim is to solve the below equations and plot m with time, i.e. dm/dt
k is unknown and needs to be estimated. For the parameter estimation, the below values for m versus t can be used. This is a dummy dataset, as I would like to get an idea if this problem is solvable. If needed, an initial guesstimate for k can be provided 6e-5 m2/bar.hr.
I have added an initial idea for the code, but not sure if my implementation of the A(H) and P(H) functions in the odes is correct. Also I need a way to estimate for k whilst fitting to the provided m vs t data.
function dydt = diffunTAR(~,y,k, h, A_H, P_H, rho_h, rho_o, wo)
dydt = zeros (2,1);
D = 2.64/1000 %mm/1000 to convert to m
r=D/2
rho_o = 1320 %kg/m3
rho_h = 1000 % kg/m3
wo=648/1000000 %weight component 1 in mg converted to kg
h= 1.5/1000 %1.5mm expressed in m
function A_H= pi*(D/2)^2 + (2/r)*(1+(rho_o/rho_h*y(2)))*(wo/rho_o);
end
function P_H = 5004.6*y(2) + 150.39;
end
%dV/dt
dydt(1)= (k/h)* function A_H* function P_H;
%dH/dt
dydt(2)= (rho_h*k/wo*h)*function A_H*function P_H;
end
tspan = linspace(0,21*24); %time in hrs for 21 days
y0 = [0 6.4800e-04];
[t,y]=ode45(#(t,y) diffunTAR(t,y, k, h, A_H0, rho_h, rho_o, wo), tspan, y0);
updated code after help
function dydt = diffunTAR(~,y,k,h,rho_h,rho_o,wo,L,r)
dydt = zeros (2,1);
%dV/dt
dydt(1)= k/h* AH * PH;
%dH/dt
dydt(2)= (rho_h*k/wo*h) * AH * PH;
AH
PH
function PH
(5004.6*y(2))+150.3;
end
function AH
pi*(r^2)+(2/r)*(1+(rho_o/rho_h*y(2)))*(wo/rho_o);
setInitialConditions (AH, 2*pi*(r)*L+2*pi*(r)^2);
end
end
D = 2.64/1000 %mm/1000 to convert to m
r=D/2
L = 10.6/100 %cm/100 to convert to m
wo=648/1000000 %weight osmotic tablets in mg converted to kg
k=6e-5 %guess for permeability
h= 1.5/1000 %1.5mm expressed in m
rho_o = 1320 %kg/m3
rho_h = 1000 % kg/m3
tspan = linspace(0,21*24); %time in hrs for 21 days
y0 = [0 6.4800e-04];
[t,y]=ode45(#(t,y) diffunTAR(t,y,k,h,rho_h,rho_o,wo,L,r), tspan, y0);

1D time dependent mass transfer and reaction in a very small gas filter

I am trying to model a PDE including advection-diffusion and reaction terms. I want to see the concentration profile after a long time (2*60*60 sec) in a very tiny slab (5 micrometer). I used method of line (ode15s) to solve this PDE but my result does not match with the experimental result. Because the outlet concentration gets maximum concentration right away (as can be seen in my plot). Does anybody have a suggestion?
clc
clear
close all
%%%%%%%%%%%parameters%%%%%%%%%%%%%%%%
global a b g Ki dx cin
Lf=5e-6; %microM
dm=8.6*10^-6; %m2/min
area=0.65; % m^-1
cin=20; %
ki=1; %mg/m3 min
Ki=0.24; %m3/mg
ux=0.5; %m/min
%%%%%%%%%%%%%%%%%%constant%%%%%%%%%%%%%%%%%%%
a=dm;
b=ux;
g=ki*Ki;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tf=2*60*60;
nx=50;
xf=Lf;
dx=xf/nx;
nt=1000;
dt=tf/nt;
x = 0:dx:xf;
t = 0:dt:tf;
N = numel(x);
u0 = zeros(N,1);
y0 = u0 ;
[t,y] = ode15s(#(t,y)fun(t,y,x,N),t,y0);
u = y(:,1:2:end);
x = (1:N)/(N+1);
plot(t/60,u(:,end))
function dydt=fun(~,y,~,N)
global a b g dx cin
bc=cin;
dydt = zeros(N,1);
i = 1;
dydt(i,:)=a*(y(i+1,:)-2*y(i,:)+bc)/(dx^2)-b*(y(i+1,:)-bc)./(2*dx)-g.*y(i+1,:);
i = 2:N-1;
dydt(i,:)=a*(y(i+1,:)-2*y(i,:)+y(i-1,:))/(dx^2)-b*(y(i+1,:)-y(i-1,:))./(2*dx)-g.*y(i,:);
i = N;
dydt(i,:)=a*(y(N,:)-2*y(i,:)+y(i-1,:))/(dx^2)-b*(y(N,:)-y(i-1,:))./(2*dx)-g.*y(i,:);
end

Solving System of Second Order Ordinary Differential Equation in Matlab

Introduction
I am using Matlab to simulate some dynamic systems through numerically solving systems of Second Order Ordinary Differential Equations using ODE45. I found a great tutorial from Mathworks (link for tutorial at end) on how to do this.
In the tutorial the system of equations is explicit in x and y as shown below:
x''=-D(y) * x' * sqrt(x'^2 + y'^2)
y''=-D(y) * y' * sqrt(x'^2 + y'^2) + g(y)
Both equations above have form y'' = f(x, x', y, y')
Question
However, I am coming across systems of equations where the variables can not be solved for explicitly as shown in the example. For example one of the systems has the following set of 3 second order ordinary differential equations:
y double prime equation
y'' - .5*L*(x''*sin(x) + x'^2*cos(x) + (k/m)*y - g = 0
x double prime equation
.33*L^2*x'' - .5*L*y''sin(x) - .33*L^2*C*cos(x) + .5*g*L*sin(x) = 0
A single prime is first derivative
A double prime is second derivative
L, g, m, k, and C are given parameters.
How can Matlab be used to numerically solve a set of second order ordinary differential equations where second order can not be explicitly solved for?
Thanks!
Your second system has the form
a11*x'' + a12*y'' = f1(x,y,x',y')
a21*x'' + a22*y'' = f2(x,y,x',y')
which you can solve as a linear system
[x'', y''] = A\f
or in this case explicitly using Cramer's rule
x'' = ( a22*f1 - a12*f2 ) / (a11*a22 - a12*a21)
y'' accordingly.
I would strongly recommend leaving the intermediate variables in the code to reduce chances for typing errors and avoid multiple computation of the same expressions.
Code could look like this (untested)
function dz = odefunc(t,z)
x=z(1); dx=z(2); y=z(3); dy=z(4);
A = [ [-.5*L*sin(x), 1] ; [.33*L^2, -0.5*L*sin(x)] ]
b = [ [dx^2*cos(x) + (k/m)*y-g]; [-.33*L^2*C*cos(x) + .5*g*L*sin(x)] ]
d2 = A\b
dz = [ dx, d2(1), dy, d2(2) ]
end
Yes your method is correct!
I post the following code below:
%Rotating Pendulum Sym Main
clc
clear all;
%Define parameters
global M K L g C;
M = 1;
K = 25.6;
L = 1;
C = 1;
g = 9.8;
% define initial values for theta, thetad, del, deld
e_0 = 1;
ed_0 = 0;
theta_0 = 0;
thetad_0 = .5;
initialValues = [e_0, ed_0, theta_0, thetad_0];
% Set a timespan
t_initial = 0;
t_final = 36;
dt = .01;
N = (t_final - t_initial)/dt;
timeSpan = linspace(t_final, t_initial, N);
% Run ode45 to get z (theta, thetad, del, deld)
[t, z] = ode45(#RotSpngHndl, timeSpan, initialValues);
%initialize variables
e = zeros(N,1);
ed = zeros(N,1);
theta = zeros(N,1);
thetad = zeros(N,1);
T = zeros(N,1);
V = zeros(N,1);
x = zeros(N,1);
y = zeros(N,1);
for i = 1:N
e(i) = z(i, 1);
ed(i) = z(i, 2);
theta(i) = z(i, 3);
thetad(i) = z(i, 4);
T(i) = .5*M*(ed(i)^2 + (1/3)*L^2*C*sin(theta(i)) + (1/3)*L^2*thetad(i)^2 - L*ed(i)*thetad(i)*sin(theta(i)));
V(i) = -M*g*(e(i) + .5*L*cos(theta(i)));
E(i) = T(i) + V(i);
end
figure(1)
plot(t, T,'r');
hold on;
plot(t, V,'b');
plot(t,E,'y');
title('Energy');
xlabel('time(sec)');
legend('Kinetic Energy', 'Potential Energy', 'Total Energy');
Here is function handle file for ode45:
function dz = RotSpngHndl(~, z)
% Define Global Parameters
global M K L g C
A = [1, -.5*L*sin(z(3));
-.5*L*sin(z(3)), (1/3)*L^2];
b = [.5*L*z(4)^2*cos(z(3)) - (K/M)*z(1) + g;
(1/3)*L^2*C*cos(z(3)) + .5*g*L*sin(z(3))];
X = A\b;
% return column vector [ed; edd; ed; edd]
dz = [z(2);
X(1);
z(4);
X(2)];

Code wont produce the value of a definite integral in MATLAB

I've had problems with my code as I've tried to make an integral compute, but it will not for the power, P2.
I've tried using anonymous function handles to use the integral() function on MATLAB as well as just using int(), but it will still not compute. Are the values too small for MATLAB to integrate or am I just missing something small?
Any help or advice would be appreciated to push me in the right direction. Thanks!
The problem in the code is in the bottom of the section labelled "Power Calculations". My integral also gets quite messy if that makes a difference.
%%%%%%%%%%% Parameters %%%%%%%%%%%%
n0 = 1; %air
n1 = 1.4; %layer 1
n2 = 2.62; %layer 2
n3 = 3.5; %silicon
L0 = 650*10^(-9); %centre wavelength
L1 = 200*10^(-9): 10*10^(-9): 2200*10^(-9); %lambda from 200nm to 2200nm
x = ((pi./2).*(L0./L1)); %layer phase thickness
r01 = ((n0 - n1)./(n0 + n1)); %reflection coefficient 01
r12 = ((n1 - n2)./(n1 + n2)); %reflection coefficient 12
r23 = ((n2 - n3)./(n2 + n3)); %reflection coefficient 23
t01 = ((2.*n0)./(n0 + n1)); %transmission coefficient 01
t12 = ((2.*n1)./(n1 + n2)); %transmission coefficient 12
t23 = ((2.*n2)./(n2 + n3)); %transmission coefficient 23
Q1 = [1 r01; r01 1]; %Matrix Q1
Q2 = [1 r12; r12 1]; %Matrix Q2
Q3 = [1 r23; r23 1]; %Matrix Q3
%%%%%%%%%%%% Graph of L vs R %%%%%%%%%%%
R = zeros(size(x));
for i = 1:length(x)
P = [exp(j.*x(i)) 0; 0 exp(-j.*x(i))]; %General Matrix P
T = ((1./(t01.*t12.*t23)).*(Q1*P*Q2*P*Q3)); %Transmission
T11 = T(1,1); %T11 value
T21 = T(2,1); %T21 value
R(i) = ((abs(T21./T11))^2).*100; %Percent reflectivity
end
plot(L1,R)
title('Percent Reflectance vs. wavelength for 2 Layers')
xlabel('Wavelength (m)')
ylabel('Reflectance (%)')
%%%%%%%%%%% Power Calculation %%%%%%%%%%
syms L; %General lamda
y = ((pi./2).*(L0./L)); %Layer phase thickness with variable Lamda
P1 = [exp(j.*y) 0; 0 exp(-j.*y)]; %Matrix P with variable Lambda
T1 = ((1./(t01.*t12.*t23)).*(Q1*P1*Q2*P1*Q3)); %Transmittivity matrix T1
I = ((6.16^(15))./((L.^(5)).*exp(2484./L) - 1)); %Blackbody Irradiance
Tf11 = T1(1,1); %New T11 section of matrix with variable Lambda
Tf2 = (((abs(1./Tf11))^2).*(n3./n0)); %final transmittivity
P1 = Tf2.*I; %Power before integration
L_initial = 200*10^(-9); %Initial wavelength
L_final = 2200*10^(-9); %Final wavelength
P2 = int(P1, L, L_initial, L_final) %Power production
I've refactored your code
to make it easier to read
to improve code reuse
to improve performance
to make it easier to understand
Why do you use so many unnecessary parentheses?!
Anyway, there's a few problems I saw in your code.
You used i as a loop variable, and j as the imaginary unit. It was OK for this one instance, but just barely so. In the future it's better to use 1i or 1j for the imaginary unit, and/or m or ii or something other than i or j as the loop index variable. You're helping yourself and your colleagues; it's just less confusing that way.
Towards the end, you used the variable name P1 twice in a row, and in two different ways. Although it works here, it's confusing! Took me a while to unravel why a matrix-producing function was producing scalars instead...
But by far the biggest problem in your code is the numerical problems with the blackbody irradiance computation. The term
L⁵ · exp(2484/L) - 1
for λ₀ = 200 · 10⁻⁹ m will require computing the quantity
exp(1.242 · 10¹⁰)
which, needless to say, is rather difficult for a computer :) Actually, the problem with your computation is two-fold. First, the exponentiation is definitely out of range of 64 bit IEEE-754 double precision, and will therefore result in ∞. Second, the parentheses are wrong; Planck's law should read
C/L⁵ · 1/(exp(D) - 1)
with C and D the constants (involving Planck's constant, speed of light, and Boltzmann constant), which you've presumably precomputed (I didn't check the values. I do know choice of units can mess these up, so better check).
So, aside from the silly parentheses error, I suspect the main problem is that you simply forgot to rescale λ to nm. Changing everything in the blackbody equation to nm and correcting those parentheses gives the code
I = 6.16^(15) / ( (L*1e+9)^5 * (exp(2484/(L*1e+9)) - 1) );
With this, I got a finite value for the integral of
P2 = 1.052916498836486e-010
But, again, you'd better double-check everything.
Note that I used quadgk(), because it's one of the better ones available on R2010a (which I'm stuck with), but you can just as easily replace this with integral() available on anything newer than R2012a.
Here's the code I ended up with:
function pwr = my_fcn()
% Parameters
n0 = 1; % air
n1 = 1.4; % layer 1
n2 = 2.62; % layer 2
n3 = 3.5; % silicon
L0 = 650e-9; % centre wavelength
% Reflection coefficients
r01 = (n0 - n1)/(n0 + n1);
r12 = (n1 - n2)/(n1 + n2);
r23 = (n2 - n3)/(n2 + n3);
% Transmission coefficients
t01 = (2*n0) / (n0 + n1);
t12 = (2*n1) / (n1 + n2);
t23 = (2*n2) / (n2 + n3);
% Quality factors
Q1 = [1 r01; r01 1];
Q2 = [1 r12; r12 1];
Q3 = [1 r23; r23 1];
% Initial & Final wavelengths
L_initial = 200e-9;
L_final = 2200e-9;
% plot reflectivity for selected lambda range
plot_reflectivity(L_initial, L_final, 1000);
% Compute power production
pwr = quadgk(#power_production, L_initial, L_final);
% Helper functions
% ========================================
% Graph of lambda vs reflectivity
function plot_reflectivity(L_initial, L_final, N)
L = linspace(L_initial, L_final, N);
R = zeros(size(L));
for ii = 1:numel(L)
% Transmission
T = transmittivity(L(ii));
% Percent reflectivity
R(ii) = 100 * abs(T(2,1)/T(1,1))^2 ;
end
plot(L, R)
title('Percent Reflectance vs. wavelength for 2 Layers')
xlabel('Wavelength (m)')
ylabel('Reflectance (%)')
end
% Compute transmittivity matrix for a single wavelength
function T = transmittivity(L)
% Layer phase thickness with variable Lamda
y = pi/2 * L0/L;
% Matrix P with variable Lambda
P1 = [exp(+1j*y) 0
0 exp(-1j*y)];
% Transmittivity matrix T1
T = 1/(t01*t12*t23) * Q1*P1*Q2*P1*Q3;
end
% Power for a specific wavelength. Note that this function
% accepts vector-valued wavelengths; needed for quadgk()
function pwr = power_production(L)
pwr = zeros(size(L));
for ii = 1:numel(L)
% Transmittivity matrix
T1 = transmittivity(L(ii));
% Blackbody Irradiance
I = 6.16^(15) / ( (L(ii)*1e+9)^5 * (exp(2484/(L(ii)*1e+9)) - 1) );
% final transmittivity
Tf2 = abs(1/T1(1))^2 * n3/n0;
% Power before integration
pwr(ii) = Tf2 * I;
end
end
end

Matlab: Kalman Filter -- How to mitigate the Warning: Matrix is singular or badly scaled

When performing the innovation update for Kalman filter, I am getting Warnings
Warning: Matrix is close to singular or badly scaled. Results may be
inaccurate. RCOND = 2.169130e-017.
Maybe due to this, the result is not accurate. How can I solve this problem? I tried introducing a loop
[R,p] = chol(Ppred);
if p> 0;
count = 300;
return;
end
where count is just a variable to stall the code until a good matrix is found. but this does not help.
UPDATE:
Linear system representation of Moving Average, MA(2) model
x_n+1 = Bw_n
y_n = Cx_n + v_n
% w = N(0,Q); v = N(0,R)
%true coefficients, h = [1 0.5 -0.9];
CODE SNIPPETS
These are the functions for the 3 modules of Kalman Filter
C = [ 1 0 0 ];
B = [1 0.5 -0.9 ;
0 1 0.5;
0 0 1];
noise_var = rand(1,1); % measurement noise
order = 2;
xpred = rand(order,1);
P = 10* eye(d,d);
A = P;
P = P + B*sqrt(noise_var)*B';
P = dlyap(A,B*B');
for i = 1:N
[xpred, Ppred] = predict(xpred,B,Ppred, Q);
[nu, S] = innovation(xpred, Ppred, y(i), C, noise_var);
[xnew, Ppred, yhat, KalmanGain] = innovation_update(xpred,Ppred,nu,S,C);
if(isnan(Ppred))
count = 300;
return;
end
end
function [xpred, Ppred] = predict(input_t,B,P, Q)
xpred = B*input_t;
Ppred = P + Q;
end
function [nu, S] = innovation(xpred, Ppred, y, C, R)
nu = y - C*xpred; %% innovation
S = R + C*Ppred*C'; %% innovation covariance
end
function [xnew, Pnew, yhat, K] = innovation_update(xpred, Ppred, nu, S, C)
K1 = Ppred*C';
K = K1'*inv(S);
xnew = xpred + K'*nu; %% new state
Pnew = Ppred - Ppred*K'*C; %% new covariance
yhat = C*xnew;
end
Numerical issues are a common problem with Kalman filters. You didn't share enough of your code to be sure (especially Q), but it is common for roundoff errors to cause P to become non-positive-definite (especially with the P update form you used).
If you google "Kalman filter numerical stability" you can find a lot of references on the subject. Simple things to try in this case would be increasing Q (aka "fictitious process noise") to avoid an ill-conditioned P, using the Joseph form of the covariance update, or forcing P to be symmetric by setting P = 0.5 * ( P + P' ).
More complex options include switching to a square root form (e.g. UDU'), or using a floating point representation with more precision (e.g. double instead of float, which is mainly hard because you're probably already at double).