plot a 10 turn coil and its magnetic field in matlab

main.m
% Define parameters
r = 1; % radius of the coil
turns = 10; % number of turns
current = 1; % current in the coil
res = 100; % resolution of the plot

% Create a 10-turn coil
theta = linspace(0, 10*2*pi, res);
x = r * cos(theta);
y = r * sin(theta);
z = current * (0:(res-1)) / res;

% Plot the coil
figure;
plot3(x, y, z, 'b', 'LineWidth', 2);
hold on;

% Calculate the magnetic field and plot it
[X,Y,Z] = meshgrid(-2*r:0.1:2*r, -2*r:0.1:2*r, 0:0.1:1);
Bx = zeros(size(X));
By = zeros(size(Y));
Bz = zeros(size(Z));

for i = 1:numel(x)
    rp = sqrt((X-x(i)).^2 + (Y-y(i)).^2);
    Bx = Bx + current * (Y-y(i)) ./ rp.^3;
    By = By - current * (X-x(i)) ./ rp.^3;
end

quiver3(X, Y, Z, Bx, By, Bz, 'r');
xlabel('X');
ylabel('Y');
zlabel('Z');
title('Magnetic Field of a 10-turn Coil');
grid on;
796 chars
36 lines

This MATLAB code defines a 10-turn coil and plots its structure as well as the associated magnetic field using quiver3 function for visualization.

related categories

gistlibby LogSnag