3d plot a magnetic field around a coil in matlab

main.m
% Define constants and parameters
mu = 4*pi*1e-7;  % Permeability of free space
I = 1;  % Current through the coil
a = 0.1;  % Radius of the coil
n = 100;  % Number of points in the coil

% Create a coil in x-y plane
theta = linspace(0, 2*pi, n);
x = a * cos(theta);
y = a * sin(theta);
z = zeros(1, n);

% Define grid for plotting
[X,Y,Z] = meshgrid(linspace(-2*a, 2*a, 50), linspace(-2*a, 2*a, 50), linspace(-2*a, 2*a, 50));

% Calculate magnetic field at each point in the grid
Bx = zeros(size(X));
By = zeros(size(Y));
Bz = zeros(size(Z));

for i = 1:numel(X)
    r = sqrt((X(i)-x).^2 + (Y(i)-y).^2 + (Z(i)-z).^2);
    B = (mu*I/(4*pi)) * (2*pi*a^2) / (r^2) * [0; 0; 1];
    Bx(i) = sum(B .* (x - X(i)) ./ r);
    By(i) = sum(B .* (y - Y(i)) ./ r);
    Bz(i) = sum(B .* (z - Z(i)) ./ r);
end

% Plot the magnetic field
quiver3(X, Y, Z, Bx, By, Bz);
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Magnetic Field around a Coil');
946 chars
35 lines

gistlibby LogSnag