clear all close all % Problem size and grid spacing, in meters. Xsize = 1; DX = 0.25; % Problem size, in samples. NX = Xsize/DX + 1; % Create an axis for output plot. Xaxis = linspace (0, Xsize, NX); % Create some space to hold the old guess and new guess. V_old = zeros(NX,1); V_new = zeros(NX,1); % Establish boundary conditions, V(x=0) = 0, V(x=1) = 1. V_old(1) = 0; V_new(1) = 0; V_old(NX) = 1; V_new(NX) = 1; % How many iterations should be done? max_iterations = 20; for iteration = 1 : max_iterations % This loop doesn't touch the exterior samples, they are unchangeable boundary conditions. % ... the interior boundary conditions will the challenging part. You can do it! for i = 2 : NX-1 V_new(i) = 0.5 * ( V_old(i-1) + V_old(i+1) ); end % Forget the old guess, overwrite it with the new guess. % This prepares us for the next iteration. V_old = V_new; % You don't have to do this, it's just a movie to help you visualize figure(1); plot (Xaxis, V_new); xlabel ('X, meters'); ylabel ('V(x), Volts'); title ('Still iterating...'); set(gcf,'Color',[1 1 1]); % white background pause(0.1); end % Plot the final converged answer. figure(2); plot (Xaxis, V_new); xlabel ('X, meters'); ylabel ('V(x), Volts'); title ('Solution to Laplace Equation'); set(gcf,'Color',[1 1 1]); % white background pause(2.0); % Example "turn-in" plot. (see homework specification) figure(3); [x,y] = meshgrid(-2:.2:2, -2:.2:2); V = x .* exp(-x.^2 - y.^2); [Ex,Ey] = gradient(V,.2,.2); contour(x,y,V),hold on, quiver(x,y,Ex,Ey) title ('Example "turn-in" plot.'); xlabel ('X, meters'); ylabel ('Y, meters'); set(gcf,'Color',[1 1 1]); % white background