%
%   Book: MATLAB-Based Electromagnetics (Pearson Prentice Hall)
%   Author: Branislav M. Notaros
%   Instructor Resources
%   (c) 2011
%
%   This MATLAB code or any part of it may be used only for educational purposes 
%   associated with the book
%
%
%


%  Visualization of the electric field due to four point charges


clear all;
close all;

EPS0 = 8.8542 * 10^(-12);
a = input('Dimension of a square at the origin in cm: ');
a = a*10^(-2);
Q = input('Charge placed at each corner of a square in nC: ');
Q = Q *10^(-9);
v = -1.5*a: 1.5/11*a : 1.5*a;
[x,y] = meshgrid(v);
N = length(x);
temp = a/2 * ones(N,N);
xsquare = [temp temp -temp -temp];
ysquare = [temp -temp temp -temp];
xtot = [x x x x];
ytot = [y y y y];
rx = (xtot - xsquare);
ry = (ytot - ysquare);
rMag = sqrt (rx.^2 + ry.^2);
rxUnit = (xtot - xsquare)./rMag;
ryUnit = (ytot - ysquare)./rMag;
Qtot = Q*ones(N,4*N);
Emag = Qtot./(4*EPS0*rMag.^2);
Ex = Emag.*rxUnit;
Ey = Emag.*ryUnit;
Etotx(:,:) = Ex(:,1:N)+Ex(:,N+1:2*N)+Ex(:,2*N+1:3*N)+Ex(:,3*N+1:4*N);
Etoty(:,:) = Ey(:,1:N)+Ey(:,N+1:2*N)+Ey(:,2*N+1:3*N)+Ey(:,3*N+1:4*N);
line([-a/2 a/2],[a/2 a/2]);
hold on;
line([a/2 a/2],[-a/2 a/2]);
line([-a/2 a/2],[-a/2 -a/2]);
line([-a/2 -a/2],[-a/2 a/2]);
plot(a/2,a/2,'bo','MarkerSize',5,'MarkerFaceColor','b');
plot(-a/2,a/2,'bo','MarkerSize',5,'MarkerFaceColor','b');
plot(a/2,-a/2,'bo','MarkerSize',5,'MarkerFaceColor','b');
plot(-a/2,-a/2,'bo','MarkerSize',5,'MarkerFaceColor','b');
quiver(v,v,Etotx,Etoty,'r');
hold off;
axis equal;
xlabel('x[m]');
ylabel('y[m]');

