% Differentiation from discrete data
X = [1 1 2 3 5 8 13 21];
Y = diff(X)
% Differentiation from discrete data
h = 0.001; % step size
X = -pi:h:pi; % domain
f = sin(X); % range
Y = diff(f)/h; % first derivative
Z = diff(Y)/h; % second derivative
plot(X(:,1:length(Y)),Y,'r',X,f,'b', X(:,1:length(Z)),Z,'k')
Differentiate a Function
% Ordinary Differentiation of a function
syms x
g = exp(x)*cos(x);
diff(g)
% 2nd order Differentiation of a function
diff(g,2)
% Partial Differentiation of a function
syms s t
f = sin(s*t);
diff(f,t)
Linear Equations
Solve for Ax=b
% A, b
A=[9.5, -2.5, 0, -2, 0; -2.5, 11, -3.5, 0, -5; 0,-3.5, 15.5, 0, -4; -2, 0, 0, 7, -3; 0, -5, -4, -3, 12];
b=[12; -16; 14; 10; -30];
% solve for Ax=b
x=A\b
x=inv(A)*b
% condition number
c=cond(A)
% norm
n=norm(A)
% eigenvalue/vector
[eigVec,eigVa]=eig(A)
% QR factorization
[Q,R]=qr(A)
% LU factorization
[L,U]=lu(A)
Polynomial fitting
t = 1:1:15;
V=[2.272 2.092 1.887 1.629 1.482 1.308 1.030 0.875 0.693 0.470 0.336 0.095 -0.163 -0.371 -0.511];
% Matlab function for polynomial fit
Zopt=polyfit(t,V,1);
Yopt=polyval(Zopt,t); % Matlab function
figure
plot(t,V, '*r')
hold on
plot(t,Yopt, '-b')
xlabel('time','fontsize',15)
ylabel('V','fontsize',15)
Exponential Fitting
RC circuit with unknown capacitor C and resistor of 5M
a) Find the capacitance C from curve fitting b) Estimate the voltage when time=32sec
Xdata = 1:1:15;
Ydata = [9.7 8.1 6.6 5.1 4.4 3.7 2.8 2.4 2.0 1.6 1.4 1.1 0.85 0.69 0.6];
% Matlab function
Zopt=polyfit(Xdata,log(Ydata),1)
R=5e6;
a0=Zopt(2);
a1=Zopt(1);
V0=exp(a0);
tau=-1/a1;
C=tau/R;
% Exponential model
Yopt=V0*exp(-1/(R*C).*Xdata);
figure
plot(Xdata,Ydata, '*r')
hold on
plot(Xdata,Yopt)
hold on
xlabel('time (s)','fontsize',15)
ylabel('V_R(volt)','fontsize',15)
1st order ODE-IVP
Solve for the response of an RC circuit with a DC input. Let tau= 4.9919; Vm=11.91;