I have seen many attempts to deal with units in Matlab, some of which I liked.
However some of them use global variables which I don't tolerate, because of the
cluttering of the workspace and the fact that they must be declared in function, before
they can actually be used.
Some other attempt attempt to attach units to each and every number in calculations.
This allows to chech the units consistency (i.e. adding, say km to kg) in calculations.
However it turns any double into a unit object and it has potentially the disadvantage
to slow calculations down.
I normally do not have a problem with unit consistency. what I have problem with is
using, say, mm instead of m, or converting mm to inches. This is also a problem during
plotting, because of the need to keep track of the units of what is being plotted.
For this reason I tend to do calculation in the MKS system (metre,kg,sec).
So when I define a variable I like to write, for instance:
diameter = 10.0 * mm;
If the value of mm is 1e-3, then the value of diameter is 1e-2, which, experessed in
metres is = 10 mm. (everything is fine)
From this point onward all the calculations that use 'diameter' can be done in the MKS,
avoiding any "order of magnitude error". The syntax above is also particularly useful in
input files where a lot of scalar parameters are defined. It provides a lot of
information at a glance.
When a variable needs to be displayed or plotted the following syntax can be used:
Also it is possible to perform units conversions in functions or on the command line.
For example the following statement converts 10 mm into inches
>> 10 * mm/in
all of this is not a my invention, being in use in at least another software. I adopted
it because for me it works very well.
To implement the syntax above I created a class called 'unit', which must be saved into
a directory called 'unitClasses'. The directory 'unitClasses' must be added to the
The function 'unitClasses\@unit\private\getStructure.m' contains a comprehensive list of
units, which can be extended as suitable.
Then by calling the method 'update(unit)', a number of classes will be created, one for
each of the units defined in 'getStructure'.
You might then have to type:
the updating can be done at any time a new unit is added to the function 'getStructure'.
from now on every time a syntax like 'diameter = 10.0 * mm;' is used a unit conversion
Your feedback is welcome
Riccardo Meldolesi (2021). UNITS conversion (https://www.mathworks.com/matlabcentral/fileexchange/17827-units-conversion), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Inspired: Automatic UNITS conversion
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!