plot a 3d magnetic field around a wire with 1a of current in matlab

To plot the 3D magnetic field around a wire with 1A of current in MATLAB, you can use the following code snippet as an example:

main.m
% Define constants
I = 1; % Current in Amperes
mu0 = 4*pi*1e-7; % Permeability of free space

% Define the wire position
wire_position = [0, 0, 0]; % Wire located at the origin
length = 1; % Length of the wire

% Define the grid for the magnetic field visualization
[X, Y, Z] = meshgrid(-2:0.1:2, -2:0.1:2, -2:0.1:2);

% Calculate the magnetic field
Bx = zeros(size(X));
By = zeros(size(Y));
Bz = zeros(size(Z));

for i = 1:numel(X)
    r = [X(i), Y(i), Z(i)] - wire_position;
    r_mag = norm(r);
    B = (mu0*I/(4*pi*r_mag^3)) * cross(r, [0, 0, 1]);
    
    Bx(i) = B(1);
    By(i) = B(2);
    Bz(i) = B(3);
end

% Plot the magnetic field
quiver3(X, Y, Z, Bx, By, Bz);
xlabel('X');
ylabel('Y');
zlabel('Z');
title('3D Magnetic Field around a Wire');
753 chars
33 lines

This code calculates the magnetic field around a wire with 1A of current located at the origin in 3D space and plots it using quiver3 for visualization. You can adjust the wire's position, length, and the grid range for more detailed visualization.

related categories

gistlibby LogSnag