% 22.3MB1 Fall 01
% Yvan Petillot
% Fields due to discrete charges distributions

clf; %Clears all figures
% define charges. Can be changed to generate new fields
charges = ...
	[1 1 1;
   -1 -1 -1;
   1 -1 1;
	-1 1 -1];
epsilon0 = 8.8e-9;
% create Mesh
[x,y] = meshgrid(-2:0.05:2,-2:0.05:2);
% Calculates potential using Coulomb Law
V = x.*0;
for i = 1 : size(charges,1)
   dist = sqrt((x-charges(i,1)).^2+(y-charges(i,2)).^2);
   V = V+1*charges(i,3)./((4*pi*epsilon0)*dist);	
end
figure(1);
contour3(x,y,V,100); % Displays the 3D contour of V
xlabel('x');
ylabel('y');
title('Potential(Volts) generated by n coplanar charges');
hold on;
% Shows where the charges are (+ for positive charges, * for negative ones)
% We can see the notion of sources and sinks very clearly here
for i = 1 : size(charges,1)
   if (charges(i,3) > 0)
      plot3(charges(i,1),charges(i,2),25,'+g');
   else
      plot3(charges(i,1),charges(i,2),-25,'*m');
   end	
end	
% Now 2 D representation
figure(2);
contour(x,y,V,100); % Displays the 2D contour of V
hold on;
% Shows where the charges are (+ for positive charges, * for negative ones)
% We can see the notion of sources and sinks very clearly here
for i = 1 : size(charges,1)
   if (charges(i,3) > 0)
      plot(charges(i,1),charges(i,2),'+g');
   else
      plot(charges(i,1),charges(i,2),'*m');
   end	
end	
% Remove singular points from the potential (for r = 0,  V = Infinity)
V = isinf(V).*0 + (1-isinf(V)).*V;
% derives fiels as E = -grad(V) = grad(-V);
[ex,ey] = gradient(-V,0.05,0.05);
ex1 = isinf(ex).*0 + (1-isinf(ex)).*ex;
ey1 = isinf(ey).*0 + (1-isinf(ey)).*ey;
ex1 = ex1(1:5:81,1:5:81);
ey1 = ey1(1:5:81,1:5:81);
% display field n new grid x1, y1 with the quiver function (show direction of field with arrows)
[x1,y1] = meshgrid(-2:0.25:2,-2:0.25:2);
quiver(x1,y1,ex1,ey1,5);
xlabel('x');  % Sets the label for the x axis
ylabel('y');  % Sets the label for the y axis
title('Potential(Volts) and Electric Field(Volt/m) for n charges in 2D'); % Sets the title of the figure
drawnow; %Draws the figure now
