% Define constants and parametersmu = 4*pi*1e-7; % Permeability of free spaceI = 1; % Current through the coila = 0.1; % Radius of the coiln = 100; % Number of points in the coil% Create a coil in x-y planetheta = 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 gridBx = zeros(size(X));
By = zeros(size(Y));
Bz = zeros(size(Z));
fori = 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 fieldquiver3(X, Y, Z, Bx, By, Bz);
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Magnetic Field around a Coil');