{"id":8495,"date":"2017-03-31T09:00:42","date_gmt":"2017-03-31T13:00:42","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=8495"},"modified":"2017-04-13T13:40:53","modified_gmt":"2017-04-13T17:40:53","slug":"physical-units-in-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2017\/03\/31\/physical-units-in-matlab\/","title":{"rendered":"Physical Units in MATLAB"},"content":{"rendered":"<div class=\"content\">\n<h3>Contents<\/h3>\n<div>\n<ul>\n<li><a href=\"#58e7bba8-52cb-4e9e-885a-a1d4bd302813\">Physical Units in MATLAB<\/a><\/li>\n<li><a href=\"#38d95775-b494-4e4c-8f79-dc4273e90344\">Why did I pick this entry?<\/a><\/li>\n<li><a href=\"#3cfeac91-4d7d-4dd5-bf02-a0877a021b0f\">Extending capabilities of the class<\/a><\/li>\n<li><a href=\"#47fdb274-882f-42cc-848a-bab69d2db23d\">Getting the unit text<\/a><\/li>\n<li><a href=\"#b9e8c389-4e24-432e-863d-84ca4fc259bb\">MathWorks tools that have units<\/a><\/li>\n<li><a href=\"#d059d2b8-7408-4ee3-b3ef-c188468a5ba2\">Should MATLAB have a units system built in?<\/a><\/li>\n<\/ul>\n<\/div>\n<h4>Physical Units in MATLAB<a name=\"58e7bba8-52cb-4e9e-885a-a1d4bd302813\"><\/a><\/h4>\n<p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/32620\">Greg&#8217;s<\/a> pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/38977-physical-units-toolbox\">Physical Units Toolbox<\/a> by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/2407391-sky-sartorius\">Sky Sartorius<\/a>.<\/p>\n<p>Wouldn&#8217;t it be nice to have units to go with those numbers you compute in MATLAB?<\/p>\n<pre class=\"codeinput\"><span class=\"comment\">% Velocity in kilometers per hour<\/span>\r\nv = 12.3 * u.kph\r\n<span class=\"comment\">% Time in seconds<\/span>\r\nt = 3.7 * u.second\r\n<span class=\"comment\">% Distance travelled<\/span>\r\nd = v * t\r\n<span class=\"comment\">% Convert distance to feet<\/span>\r\nu2num(d, u.foot)\r\n<span class=\"comment\">% Another method to convert distance to feet<\/span>\r\nd\/u.ft\r\n<\/pre>\n<pre class=\"codeoutput\">v =\r\n\r\n    3.4167\r\n\r\n\t\tm\r\n\t\t-\r\n\t\ts\r\n\r\n\r\nt =\r\n\r\n    3.7000\r\n\r\n\t\t s\r\n\r\nd =\r\n\r\n   12.6417\r\n\r\n\t\t m\r\n\r\nans =\r\n\r\n   41.4753\r\n\r\n\r\nans =\r\n\r\n   41.4753\r\n\r\n<\/pre>\n<p>I&#8217;ve always wanted this functionality in both MATLAB and Simulink. When I was a student in University, MATLAB was my favorite programming tool, but I didn&#8217;t use it much for engineering homework, as there were other tools that had nice worksheets and included units with unit conversions and computations.<\/p>\n<p>Even as an employee of MathWorks I&#8217;ve found myself using other math software to assist with computations that required careful tracking and conversion of units.<\/p>\n<h4>Why did I pick this entry?<a name=\"38d95775-b494-4e4c-8f79-dc4273e90344\"><\/a><\/h4>\n<p>The two key elements for me are it is:<\/p>\n<div>\n<ul>\n<li>Easy to use<\/li>\n<li>Well documented<\/li>\n<\/ul>\n<\/div>\n<p>The inclusion of units by just simply multiplying by the desired unit is a well thought out mechanism. Also, there are of course functions and methods to extract values of a specific unit type.<\/p>\n<p>And there is unit consistency checking, making sure that you don&#8217;t attempt to do things like convert a distance to a temperature.<\/p>\n<pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    u2num(d, u.kelvin)\r\n<span class=\"keyword\">catch<\/span> Me\r\n    disp(Me.message);\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre>\n<pre class=\"codeoutput\">Incompatible input dimensions\r\n<\/pre>\n<p>The attention to detail and planning the functionality provides for easy use of this tool. For example, Sky included functions for unit conversion for standard MATLAB variables, not just the unit class. This means you don&#8217;t have to think about whether or not a particular variable is of the <tt>DimVar<\/tt> class or not.<\/p>\n<pre class=\"codeinput\">a = pi;\r\nu2num(a)\r\n<\/pre>\n<pre class=\"codeoutput\">ans =\r\n\r\n    3.1416\r\n\r\n<\/pre>\n<h4>Extending capabilities of the class<a name=\"3cfeac91-4d7d-4dd5-bf02-a0877a021b0f\"><\/a><\/h4>\n<p>The organization and documentation of the code makes it pretty easy to add additional functions that enable conversions. For example, many times I may want to include the result of a particular computation as a variable in Simulink. With the addition of units in Simulink (R2016a) there can be consistency between the environments.<\/p>\n<pre class=\"codeinput\">g = 9.81 *u.m\/u.s^2\r\n<span class=\"comment\">% Create Simulink.Parameter object with the same value and units as \"g\"<\/span>\r\ngParam = u2param(g)\r\n<\/pre>\n<pre class=\"codeoutput\">g =\r\n\r\n    9.8100\r\n\r\n\t\t m\r\n\t\t---\r\n\t\ts^2\r\n\r\n\r\ngParam = \r\n\r\n  Parameter with properties:\r\n\r\n          Value: 9.8100\r\n      CoderInfo: [1\u00d71 Simulink.CoderInfo]\r\n    Description: ''\r\n       DataType: 'auto'\r\n            Min: []\r\n            Max: []\r\n           Unit: 'm\/s^2'\r\n     Complexity: 'real'\r\n     Dimensions: [1 1]\r\n\r\n<\/pre>\n<p>Now the units engine in Simulink will be able to help with things like units consistency checking when this variable &#8220;gParam&#8221; is used in the Simulink model.<\/p>\n<pre class=\"codeinput\">type <span class=\"string\">u2param<\/span>\r\ntype <span class=\"string\">getUnitString<\/span>\r\n<\/pre>\n<pre class=\"codeoutput\">function p = u2param(v)\r\n\r\n    assert(isa(v, 'DimVar'));\r\n    \r\n    s = getUnitString(v);\r\n    \r\n    p = Simulink.Parameter(u2num(v));\r\n    p.Unit = s;\r\nend\r\n    \r\n\r\nfunction s = getUnitString(v)\r\n\r\n    assert(isa(v, 'DimVar'));\r\n    \r\n    [num, dem] = display(v);\r\n    \r\n    s = sprintf('%s\/%s', num, dem);\r\n\r\nend\r\n<\/pre>\n<h4>Getting the unit text<a name=\"47fdb274-882f-42cc-848a-bab69d2db23d\"><\/a><\/h4>\n<p>Getting the units of a value as a string that can be interpreted by other MATLAB and Simulink tools would be helpful.<\/p>\n<p>Technically the UNITSOF function returns the unit string of an object, but in a specialized format.<\/p>\n<pre class=\"codeinput\">unitsOf(g)\r\n<\/pre>\n<pre class=\"codeoutput\">[m^1][s^-2]\r\n<\/pre>\n<p>This can be remedied pretty easily with the following:<\/p>\n<pre class=\"codeinput\">[numerator, denominator] = display(g);\r\n[numerator <span class=\"string\">'\/'<\/span> denominator]\r\n<\/pre>\n<pre class=\"codeoutput\">ans =\r\n\r\n    'm\/s^2'\r\n\r\n<\/pre>\n<p>And of course as or R2017a, you can do things like:<\/p>\n<pre class=\"codeinput\">numerator + <span class=\"string\">\"\/\"<\/span> + denominator\r\n<\/pre>\n<pre class=\"codeoutput\">ans = \r\n\r\n    \"m\/s^2\"\r\n\r\n<\/pre>\n<h4>MathWorks tools that have units<a name=\"b9e8c389-4e24-432e-863d-84ca4fc259bb\"><\/a><\/h4>\n<p>There are some addons that do support physical units.<\/p>\n<p><a title=\"https:\/\/www.mathworks.com\/help\/releases\/R2017a\/simulink\/units.html (link no longer works)\">Simulink<\/a> now has a notion of units on signal lines.<\/p>\n<p>The <a title=\"https:\/\/www.mathworks.com\/help\/releases\/R2017a\/physmod\/simscape\/ug\/how-to-specify-units-in-block-dialog-boxes.html (link no longer works)\">Simscape<\/a> products all require the use of specific units when defining properties of physical elements.<\/p>\n<p>The <a title=\"https:\/\/www.mathworks.com\/help\/releases\/R2017a\/symbolic\/units-of-measurement-tutorial.html (link no longer works)\">Symbolic Math Toolbox<\/a> also has some <a href=\"https:\/\/www.mathworks.com\/help\/symbolic\/symunit.html\">capability<\/a> to apply physical units to calculations and enable symbolic manipulations as well.<br \/>\n<a href=\"https:\/\/blogs.mathworks.com\/pick\/files\/symunit_example.jpg\"><img decoding=\"async\" loading=\"lazy\" width=\"1296\" height=\"384\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/symunit_example.jpg\" alt=\"\" class=\"alignnone size-full wp-image-8526\" \/><\/a><\/p>\n<h4>Should MATLAB have a units system built in?<a name=\"d059d2b8-7408-4ee3-b3ef-c188468a5ba2\"><\/a><\/h4>\n<p>Let us know <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=8495#respond\"> here<\/a>.<\/p>\n<p><script language=\"JavaScript\"> <!-- \n    function grabCode_bd918034890c47039085aa2a63faf9a5() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='bd918034890c47039085aa2a63faf9a5 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' bd918034890c47039085aa2a63faf9a5';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        copyright = 'Copyright 2017 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('<\/p>\n\n\n\n\n<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\n\n\n\n\n<p>\\n');\n\n        d.title = title + ' (MATLAB code)';\n        d.close();\n    }   \n     --> <\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight: lighter; font-style: italic; color: gray;\">\n<a><span style=\"font-size: x-small; font-style: italic;\">Get<br \/>\nthe MATLAB code<noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>Published with MATLAB\u00ae R2017a<\/p>\n<\/div>\n<p><!--\nbd918034890c47039085aa2a63faf9a5 ##### SOURCE BEGIN #####\n%% Physical Units in MATLAB\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/32620 Greg's>\n% pick this week is <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/38977-physical-units-toolbox % Physical Units Toolbox> by <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/2407391-sky-sartorius % Sky Sartorius>.\n%\n% Wouldn't it be nice to have units to go with those numbers you compute\n% in MATLAB?\n\n% Velocity in kilometers per hour\nv = 12.3 * u.kph\n% Time in seconds\nt = 3.7 * u.second\n% Distance travelled\nd = v * t\n% Convert distance to feet\nu2num(d, u.foot)\n% Another method to convert distance to feet\nd\/u.ft\n\n%%\n% I've always wanted this functionality in both MATLAB and Simulink. When\n% I was a student in University, MATLAB was my favorite programming tool, but\n% I didn't use it much for engineering homeworks, as there were other tools that\n% had nice worksheets and included units with unit conversions and computations.\n%\n% Even as an employee of MathWorks I've found myself using other math software\n% to assist with computations that required careful tracking and conversion of\n% units.\n%% Why did I pick this entry?\n% The two key elements for me are it is:\n%\n% * Easy to use\n% * Well documented\n%\n% The inclusion of units by just simply multipling by the desired unit is\n% a well thought out mechanism. Also, there are of course functions and methods\n% to extract values of a specific unit type.\n%\n% And there is unit consistency checking, making sure that you don't attempt\n% to do things like convert a distance to a temperature.\n%%\ntry\nu2num(d, u.kelvin)\ncatch Me\ndisp(Me.message);\nend\n%%\n%\n%\n% The attention to detail and planning the functionality provides for easy\n% use of this tool.  For example, Sky included functions for unit conversion for\n% standard MATLAB variables, not just the unit class.  This means you don't have\n% to think about whether or not a particular variable is of the |DimVar| class\n% or not.\n%%\na = pi;\nu2num(a)\n%% Extending capabilities of the class\n% The organization and documentation of the code makes it pretty easy to add\n% additional functions that enable conversions.  For example, many times I may\n% want to include the result of a particular computation as a variable in Simulink.\n% With the addition of units in Simulink (R2016a) there can be consistency between\n% the environments.\n%%\ng = 9.81 *u.m\/u.s^2\n% Create Simulink.Parameter object with the same value and units as \"g\"\ngParam = u2param(g)\n%%\n% Now the units engine in Simulink will be able to help with things like\n% units consistency checking when this variable \"gParam\" is used in the Simulink\n% model.\n\ntype u2param\ntype getUnitString\n%% Getting the unit text\n% Getting the units of a value as a string that can be interpreted by other\n% MATLAB and Simulink tools would be helpful.\n%\n% Technically the UNITSOF function returns the unit string of an object,\n% but in a specialized format.\n%%\nunitsOf(g)\n%%\n% This can be remedied pretty easily with the following:\n\n[numerator, denominator] = display(g);\n[numerator '\/' denominator]\n%%\n% And of course as or R2017a, you can do things like:\n\nnumerator + \"\/\" + denominator\n%% MathWorks tools that have units\n% There are some addons that do support physical units.\n%\n% <https:\/\/www.mathworks.com\/help\/releases\/R2017a\/simulink\/units.html Simulink>\n% now has a notion of units on signal lines.\n%\n% The <https:\/\/www.mathworks.com\/help\/releases\/R2017a\/physmod\/simscape\/ug\/how-to-specify-units-in-block-dialog-boxes.html % Simscape> products all require the use of specific units when defining properties\n% of physical elements.\n%\n% The <https:\/\/www.mathworks.com\/help\/releases\/R2017a\/symbolic\/units-of-measurement-tutorial.html % Symbolic Math Toolbox> also has some capability to apply physical units to calculations\n% and enable symbolic manipulations as well.\n%\n%\n%% Should MATLAB have a units system built in?\n% Let us know <https:\/\/blogs.mathworks.com\/pick\/?p=8495#respond here>.\n##### SOURCE END ##### bd918034890c47039085aa2a63faf9a5\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/symunit_example.jpg\" onError=\"this.style.display ='none';\" \/><\/div>\n<p>\nContents<\/p>\n<p>Physical Units in MATLAB<br \/>\nWhy did I pick this entry?<br \/>\nExtending capabilities of the class<br \/>\nGetting the unit text<br \/>\nMathWorks tools that have units<br \/>\nShould MATLAB have a units system built&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2017\/03\/31\/physical-units-in-matlab\/\">read more >><\/a><\/p>\n","protected":false},"author":36,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/8495"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/36"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=8495"}],"version-history":[{"count":7,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/8495\/revisions"}],"predecessor-version":[{"id":8527,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/8495\/revisions\/8527"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=8495"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=8495"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=8495"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}