% IAP 2006 Introduction to MATLAB % Ordinary Differential Equations (ODE) % EXAMPLE 3 Current and Voltage through a Parallel RC Circuit % Based on the MATLAB Mastery Tutorial at: % https://web.mit.edu/tm/matlab_mastery_I/setup/Start.htm % Find a numerical solution for the current I and voltage drop V for a % capacitor with initial charge q0 draining through a resistor R. % A. Solve ODE based on Ohm's law for RC circuit % ODE for the capacitor's rate of discharge is: % R * (dq/dt) + q / C = 0 % where R is the resistance of the resistor in Ohms, % and C is the capacitance of the capacitor in farads. % The equation can be re-written as: dq/dt = -1/(R*C) * q % A1. Define global variables C and R % Global variables can be accessed from other files. For example: global R C C = 0.002 R = 150 % A2. Define function Dq = ode(t, q) % Dq is defined in the function M-file called ode.m % Dq is a variable that stands for dq/dt % See file ode.m for the definition of Dq before proceeding here % A3. Define condition at time t=0 % The charge is q0 in coulombs; for example: q0 = -0.001 % We can call the function ode to compute dt/dq at t=0 Dq0 = ode(0, q0) % A4. Compute solution of ODE % Define time interval tspan = [0 : 0.01 : 1] % A5. Compute numerical solution using the ode45 function % ode45 is a built-in function for solving nonstiff diferrential equations. [t, q] = ode45( @ode, tspan, q0 ) % Note that the function ode is passed to ode45 as a Function Handle @ode. % A6. Plot the numerical solution plot(t, q, 'g') grid on % A7. Compute the current I over time % The current is the derivative of the charge q i.e. dq/dt. % To compute I over time, we pass the vectors t and q to ode: I = ode(t, q); % A8. Compute the voltage drop across the resistor over time V = I*R % A9. Plot I and V on a semilogarithmic plot semilogy(t, I, 'r-') hold on semilogy(t, V, 'b-') grid on hold off xlabel('Time') ylabel('Voltage drop V and current I') legend('V', 'I') title('RC Circuit') % A10. See Solving 2nd Order ODE in the MATLAB Mastery Tutorial % Sellect the Differential Equations module and go to part 2 of it % https://web.mit.edu/tm/matlab_mastery_I/setup/Start.htm