A MatLab Example in Electrostatics
Courtesy of Professor James Lockhart
This example will consider a system consisting of a unit positive
charge at location x = 0.95, y = 0.95,
and a unit negative charge at
location x = 1.95, y = 1.95 .
(Note that this type of system is found in the solution to a common
image charge problem.)
We choose the location so that none of our grid points will fall on a charge
location and cause the potential to blow up.
We will make a contour plot and a 3-D plot of the potential,
a 3-D plot of the Laplacian,
and a vector plot of the electric field for this system.
(Note that the >> symbol indicates the MatLab screen prompt
and should not be typed.
Note also that you can save any useful calculational tools which you
develop in MatLab as ".m" files for later use.)
MatLab Command Comments
>>x=0:.1:3; This creates an array x with values 0,
0.1, 0.2,...3.0 . The ; at the end supresses the
screen display of the result.
>>y=0:.1:3; Similar statement for the y array.
>>y(1:4) This prints the first four values of the y array.
>>[xx,yy]=meshgrid(x,y); meshgrid creates an x-y grid with coordinates of
the points given by the vectors x and y; the
matrices xx and yy contain the x-values at the
grid points and the y-values, respectively.
>>xx(14:16,14:16) Prints the x values for the center part of the grid.
>>yy(14:16,14:16) Prints the y values for the center part of the grid.
>>posd2=(xx-.95).^2+(yy-.95).^2; We calculate the distance squared of each grid point
from the positive charge. The .^2 causes the
squaring to be done on an element-by-element basis,
rather than causing a matrix multiplication.
>>posd=sqrt(posd2); We use the square root function to get the distance.
>>pos=posd.^(-1); We calculate the potential from the positive charge.
>>negd2=(xx-1.95).^2+(yy-1.95).^2; Distance-squared from the negative charge
>>neg=negd.^(-1); Magnitude of negative charge's potential.
>>zz=pos-neg; Superpose the two potentials.
>>contour(zz,21) Make a contour plot of the potential with 21 contours.
Using an odd number of contours lets us see the
>>mesh(zz) A 3-D mesh plot of the potential.
>>surf(zz) A surface plot.
>>lp=del2(zz); We calculate the 5-point Laplacian of the potential.
>>mesh(lp) A 3-C mesh plot of the Laplacian. Noet that the
5-point numerical Laplacian will show non-zero values
close to the charge location.
>>[px,py]=gradient(zz,.1,.1); We use the gradient function to calculate the electrid
field from the potential. The .1 parameters are the
appropriate dx and dy values.
>>quiver(x,y,px,py,2); This gives a vector plot of the field; the last
parameter gives a scaling factor.