This Matlab code illustrates the Euler method applied to the RLC circuit problem.
clear all, close all, clc C=1; % Capacity between 0 and 4 makes (0,0) an unstable equilibrium M=10; % number of samples points x1min=-2; x1max=2; % domain specification x2min=-2; x2max=2; [X1,X2]=meshgrid(x1min:(x1max-x1min)/M:x1max,x2min:(x2max-x2min)/M:x2max); dX1=X1-X1.^3-X2; % x1-component dX2=X1/C; % x2-component quiver(X1,X2,dX1,dX2); % matlab routine axis([x1min x1max x2min x2max]); title('Direction field (the vectors are rescaled!)'); hold on xlabel('Current'); ylabel('Voltage');
Choose initial condition and terminal time T, plus the time step h
x=[-1;-1.5]; T = 10; % terminal time h=0.1; % time step (the smaller, the better) N = floor(T/h); % numer of iterations
This is the iteration and the resultion approximate solution in the phase portrait.
for n=1:N rhs = [x(1)-x(1)^3-x(2); x(1)/C]; xnew = x + h*rhs; plot([x(1),xnew(1)], [x(2),xnew(2)],'-ro',... 'MarkerFaceColor','k','MarkerSize',2), hold on x = xnew; end xlabel('x1'); ylabel('x2');