% Unit 2 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%=====================================
% 3D force field of one single charge
%=====================================
clear all
close all
clc

% position of electrical charge
x0 = +0.25;
y0 = -0.15;
z0 = +0.10;

% range and # of points
Nmesh = 10;
xmin  = -1.25;
xmax  = +1.00;
ymin  = -0.75;
ymax  = +1.15;
zmin  = -0.95;
zmax  = +1.23;

% generate a linearly spaced mesh in x and y
xmesh = linspace(xmin,xmax,Nmesh);
ymesh = linspace(ymin,ymax,Nmesh);
zmesh = linspace(zmin,zmax,Nmesh);
[x,y,z] = meshgrid(xmesh,ymesh,zmesh);

% calculate the scalar field at every mesh point (e.g. 1/r)
Upot = -1./sqrt((x-x0).^2+(y-y0).^2+(z-z0).^2);

% calculate the force field
[Fx,Fy,Fz] = gradient(-Upot);

% plot the force vectors
quiver3(x,y,z,Fx,Fy,Fz)
colorbar
