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


%  Three point charges in Cartesian coordinate system


clear all;
close all;
EPS0 = 8.8542*10^(-12); 

 N = 2;
 x = [0 0]*100;
 y = [1 0]*100;
 z = [0 1]*100;
 xp = 100;
 yp = 0;
 zp = 0;

 Q = [-2 2];
 Qp = 1;


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

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

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

F = (ones(3,1)*(Qp*Q./(4*pi*EPS0*r.^2))).*uVec;  %each component
Ftot = sum(F,2);
Fmag = vectorMag(Ftot);
Fuv = (Ftot/Fmag)';

% Output

fprintf('Magnitude of resultant force at point P is %f mN.\n',Fmag*1000 );
disp('Unit vector of resultant force :');
disp(Fuv);

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] + F(:,i)',1/Fmag,'b',0);
hold on;
end;
vecPlot3D([xp yp zp],[xp yp zp] + Ftot',1/Fmag,'r',1);
text(1.4*xp,1.4*yp,1.4*zp,'Total electric force','Color','r');

hold off;
axis equal;
xlabel('x[m]');
ylabel('y[m]');
zlabel('z[m]');
title({'Force from ',int2str(N),'-point charges'});
