%
%   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
%
%
%



%  Electric field due to multiple charges


clear all;
close all;
EPS0 = 8.8542*10^(-12); 
N = input('Enter the number of point charges: ');

% Input

for i = 1:N
    x(i) = input(['Enter the X coordinate in cm for charge ',int2str(i) ,':  ']);
    y(i) = input(['Enter the Y coordinate in cm for charge ', int2str(i),':  ']);
    z(i) = input(['Enter the Z coordinate in cm for charge ', int2str(i),':  ']);
    Q(i) = input(['Enter the charge in nC for charge ',...
        int2str(i),':  ']);
end
xp = input('Enter the X coordinate in cm of the point of interest: ');
yp = input('Enter the Y coordinate in cm of the point of interest: ');
zp = input('Enter the Z coordinate in cm of the point of interest: ');

x = x * 10^(-2);
y = y * 10^(-2);
z = z * 10^(-2);
Q = Q * 10^(-9);

xp = xp * 10^(-2);
yp = yp * 10^(-2);
zp = zp * 10^(-2);

% Compute distance and direction between observation point and each charge

r = sqrt((xp - x).^2 + (yp - y).^2 + (zp - z).^2);
ux = (xp - x)./r;
uy = (yp - y)./r;
uz = (zp - z)./r;
uVec = [ux; uy; uz];

% Electric field computation

E = (ones(3,1)*(Q./(4*pi*EPS0*r.^2))).*uVec;
Etot = sum(E,2);
Emag = vectorMag(Etot);
Euv = (Etot/Emag)';

%Output

fprintf('Magnitude of resultant field at point P is %f mV/m.\n',Emag*1000 );
disp('Unit vector of resultant force :');
disp(Euv);

figure(1);
plot3(0,0,0,'k');
hold on;
for i=1:N
plot3(x(i),y(i),z(i),'o','MarkerSize',10,'MarkerFaceColor','b');
line ([xp , x(i)],[yp,y(i)], [zp,z(i)],'LineStyle',':');
hold on;
vecPlot3D([xp yp zp],[xp yp zp] + E(:,i)',1/Emag,'b',0);
hold on;
end;
vecPlot3D([xp yp zp],[xp yp zp] + Etot',1/Emag,'r',0);
text(1.1*xp,1.1*yp,1.1*zp,'Total electric field','Color','r');

hold off;
axis equal;
xlabel('x');
ylabel('y');
zlabel('z');
title({'Electric field due to ',int2str(N),'-point charges'});



