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

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

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

% range and # of points
Nmesh = 100;
xmin  = -1.25;
xmax  = +1.00;
ymin  = -0.75;
ymax  = +1.15;

% we could also use an anonynous function for dist2D()
%dist2D = @(x1,x2,y1,y2)(sqrt((x1-x2).^2+(y1-y2).^2));

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

% calculate the scalar field at every mesh point (e.g. 1/r)
Upot = -1./dist2D(x,y,x0,y0);

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

% plot the force vectors
figure(2)
quiver(x,y,Fx,Fy)
colorbar
