Magnetic fields of solenoids and magnets

Analytical calculation of the magnetic field of finite solenoids (which is also the field of cylindrical magnets) and cuboidal magnets


Updated 5 Nov 2021

View License

1) The file 'FieldBar.m' calculates the cuboidal magnet field with the formulas of Camacho & Sosa, Rev. Mex. E, E 59, 8-17, 2013 (see, which have been corrected (see the documentation).
2) The file 'FieldSolenoid.m' calculates the cylindrical magnet (=solenoid) field with (corrected) formula of Callaghan & Maslen (1960) and Derby & Olbert, Am. J. Phys. 78, 229 , 2010 (see respectively and See details in the documentation.
3) The file 'PlotField.m' plot the magnetic field in various cases, for cylindrical magnets (=solenoids) and cuboidal magnets.
WARNING/REQUIREMENT: the included files whose name start with 'Elliptic' calculate the needed elliptic integrals (these files are actually the functions I have released at, by relying on '' by Thomas Hoffend, which has to be downloaded at
[Alternatively, 'Elliptic Integrals' by Moiseev Igor ( can be used by commenting/uncommenting 2 lines in the files whose name start with 'Elliptic']

Cite As

David CEBRON (2023). Magnetic fields of solenoids and magnets (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2019a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by:

Inspired: Magnetic Field Modeling

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes

Small misprint in the documentation


Thanks to Max Oberländer : correction of an error present in the formula of Camacho & Sosa (2013), on which my script relies for cuboidal magnets. See details in the enclosed documentation.


Only changed the picture


Documentation added (with details on the analytical expressions used).