{"id":72,"date":"2007-01-05T12:46:45","date_gmt":"2007-01-05T17:46:45","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=72"},"modified":"2017-06-02T08:19:20","modified_gmt":"2017-06-02T13:19:20","slug":"class-initialization-for-variables","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/01\/05\/class-initialization-for-variables\/","title":{"rendered":"Class Initialization for Variables"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>A while ago, I wrote an article sharing some ideas for <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=38\">Programming for Multiple Datatypes<\/a>. Recently, a colleague asked me a related question for writing some M-code to be used in an embedded MATLAB block in <a href=\"https:\/\/www.mathworks.com\/products\/simulink\/\">Simulink<\/a>.  He also wanted to be able to generate code from it, using <a href=\"https:\/\/www.mathworks.com\/products\/rtw\/\">https:\/\/www.mathworks.com\/products\/rtw\/<\/a> Real-Time Workshop&gt;, and not use it only for simulation.  Together, we tried several ideas.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Conversion to a Known Class<\/a><\/li>\r\n         <li><a href=\"#5\">Conversion to the Class of Another Variable<\/a><\/li>\r\n         <li><a href=\"#12\">Methods that Should (Usually) Work for All Types<\/a><\/li>\r\n         <li><a href=\"#14\">Other Methods or Preferences<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Conversion to a Known Class<a name=\"1\"><\/a><\/h3>\r\n   <p>It's typically straight-forward to convert data into a known class. Simply use the name of the class as the conversion method.\r\n       If that particular conversion is supported, mission accomplished.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">md = magic(3);\r\nclass(md)<\/pre><pre style=\"font-style:oblique\">ans =\r\ndouble\r\n<\/pre><p><tt>md<\/tt> is a double precision magic square.  Now convert <tt>md<\/tt> to <tt>uint16<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">mu16 = uint16(md);\r\nclass(mu16)<\/pre><pre style=\"font-style:oblique\">ans =\r\nuint16\r\n<\/pre><p>Comparing the arrays, <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/isequal.html\"><tt>isequal<\/tt><\/a> says they are the same since <tt>isequal<\/tt> ignores class or type in comparison.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">eqvals = isequal(md, mu16)<\/pre><pre style=\"font-style:oblique\">eqvals =\r\n     1\r\n<\/pre><p>If you want to check the classes are also the same, you can do something like this.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sameclass = strcmp(class(md),class(mu16))<\/pre><pre style=\"font-style:oblique\">sameclass =\r\n     0\r\n<\/pre><h3>Conversion to the Class of Another Variable<a name=\"5\"><\/a><\/h3>\r\n   <p>If you want to write a generic algorithm and you need to be able to handle inputs of a variety of classes, there are some\r\n      techniques you can use to ensure that the calculations are done in the class you want.\r\n   <\/p>\r\n   <p>If you want to initialize some variables in your calculation to 0, but in the class of the input, you could use a <tt>switch<\/tt> statement and check all of the builtin types.  This is tedious, error-prone, and does not scale well.\r\n   <\/p>\r\n   <p>You could also use the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/zeros.html\"><tt>zeros<\/tt><\/a> function with the final <tt>classname<\/tt> argument.  This works for builtin numeric types.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">valsaved = zeros(1,1,class(mu16));<\/pre><p>Another method that also works for builtin types is using the function <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cast.html\"><tt>cast<\/tt><\/a>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">b = cast(0.0,class(mu16));<\/pre><p>What do we do if we have an input that behaves like a builtin numeric clas but isn't built in?  Some examples might be the\r\n      <a href=\"https:\/\/www.mathworks.com\/help\/symbolic\/sym.html\"><tt>sym<\/tt><\/a> object in the Symbolic Math Toolbox (assuming the variable contains values that can be converted to numeric ones) or the\r\n      <a href=\"https:\/\/www.mathworks.com\/help\/fixedpoint\/ref\/fi.html\"><tt>fi<\/tt><\/a> fixed-point object from the Fixed-Point Toolbox.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">msym = sym(md);\r\nmfi = fi(md);\r\nwhos<\/pre><pre style=\"font-style:oblique\">  Name           Size            Bytes  Class              Attributes\r\n\r\n  ans            1x6                12  char                         \r\n  b              1x1                 2  uint16                       \r\n  eqvals         1x1                 1  logical                      \r\n  fhfi           1x1                16  function_handle              \r\n  fhsym          1x1                16  function_handle              \r\n  md             3x3                72  double                       \r\n  mfi            3x3                    embedded.fi                  \r\n  msym           3x3               622  sym                          \r\n  mu16           3x3                18  uint16                       \r\n  sameclass      1x1                 1  logical                      \r\n  valsaved       1x1                 2  uint16                       \r\n  zfi            1x1                    embedded.fi                  \r\n  zsym           1x1               126  sym                          \r\n  zsym2          1x1               126  sym                          \r\n  zsym3          1x1               126  sym                          \r\n\r\n<\/pre><p>Here's a way to convert to an arbitrary class, using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/str2func.html\"><tt>str2func<\/tt><\/a><\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fhsym = str2func(class(msym));\r\nzsym = fhsym(0.0);\r\nfhfi = str2func(class(mfi));\r\nzfi = fhfi(0.0);\r\nwhos<\/pre><pre style=\"font-style:oblique\">  Name           Size            Bytes  Class              Attributes\r\n\r\n  ans            1x6                12  char                         \r\n  b              1x1                 2  uint16                       \r\n  eqvals         1x1                 1  logical                      \r\n  fhfi           1x1                16  function_handle              \r\n  fhsym          1x1                16  function_handle              \r\n  md             3x3                72  double                       \r\n  mfi            3x3                    embedded.fi                  \r\n  msym           3x3               622  sym                          \r\n  mu16           3x3                18  uint16                       \r\n  sameclass      1x1                 1  logical                      \r\n  valsaved       1x1                 2  uint16                       \r\n  zfi            1x1                    embedded.fi                  \r\n  zsym           1x1               126  sym                          \r\n  zsym2          1x1               126  sym                          \r\n  zsym3          1x1               126  sym                          \r\n\r\n<\/pre><p>There is a limitation to this method for Simulink users who want to use embedded MATLAB in the generated code since <tt>str2func<\/tt> is not supported for that situation.\r\n   <\/p>\r\n   <h3>Methods that Should (Usually) Work for All Types<a name=\"12\"><\/a><\/h3>\r\n   <p>So, how to get that initial value to 0 in the right class?  Do some arithmetic!  Here are two possibilites, illustrated with\r\n      the <tt>sym<\/tt> variable <tt>msym<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">zsym2 = 0*msym(1);\r\nzsym3 = msym(1)-msym(1);<\/pre><p>Why do I say \"usually\" in the title of this section?  The calculations should be supported for classes that behave numerically.<\/p>\r\n   <p>Well, first, it allows me to refer you to a great numerical computing reference.<\/p>\r\n   <div>\r\n      <ul>\r\n         <li>Numerical Methods that [Usually] Work, Forman S. Acton, Harper &amp; Row, Publishers, ISBN 0883854503 (first published in 1970.\r\n             On my copy the words on the cover are embossed in gold ink, except the word \"usually\" which is simply impressed.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Second, I have to admit that these methods only work for finite values of the first input.  What would you do if you had to\r\n      guard against non-finite values?\r\n   <\/p>\r\n   <h3>Other Methods or Preferences<a name=\"14\"><\/a><\/h3>\r\n   <p>Do you have other methods that would work for the conversion to an unknown class?  Or preferences on a method to use?  If\r\n      so, please <a href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/01\/05\/class-initialization-for-variables\/#respond\">post here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_79cfe78b3d0245d7a73be9064f871d15() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='79cfe78b3d0245d7a73be9064f871d15 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 79cfe78b3d0245d7a73be9064f871d15';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Loren Shure';\r\n        copyright = 'Copyright 2007 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_79cfe78b3d0245d7a73be9064f871d15()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.3<br><\/p>\r\n<\/div>\r\n<!--\r\n79cfe78b3d0245d7a73be9064f871d15 ##### SOURCE BEGIN #####\r\n%% Class Initialization for Variables\r\n% A while ago, I wrote an article sharing some ideas for\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=38 Programming for Multiple Datatypes>.\r\n% Recently, a colleague asked me a related question for writing some M-code\r\n% to be used in an embedded MATLAB block\r\n% in <https:\/\/www.mathworks.com\/products\/simulink\/ Simulink>.  He also wanted to be\r\n% able to generate code from it, using https:\/\/www.mathworks.com\/products\/rtw\/ Real-Time Workshop>,\r\n% and not use it only for simulation.  Together, we tried several ideas.\r\n%% Conversion to a Known Class\r\n% It's typically straight-forward to convert data into a known class.\r\n% Simply use the name of the class as the conversion method.  If that\r\n% particular conversion is supported, mission accomplished.\r\nmd = magic(3);\r\nclass(md)\r\n%%\r\n% |md| is a double precision magic square.  Now convert |md| to\r\n% |uint16|.\r\nmu16 = uint16(md);\r\nclass(mu16)\r\n%%\r\n% Comparing the arrays, <https:\/\/www.mathworks.com\/help\/matlab\/ref\/isequal.html |isequal|>\r\n% says they are the same since |isequal| ignores class or type in comparison.  \r\neqvals = isequal(md, mu16)\r\n%%\r\n% If you want to check the classes are also the same, you can do something\r\n% like this.\r\nsameclass = strcmp(class(md),class(mu16))\r\n%% Conversion to the Class of Another Variable\r\n% If you want to write a generic algorithm and you need to be able to\r\n% handle inputs of a variety of classes, there are some techniques you can\r\n% use to ensure that the calculations are done in the class you want.  \r\n%%\r\n% If you want to initialize some variables in your calculation to 0, but in\r\n% the class of the input, you could use a |switch| statement and check all\r\n% of the builtin types.  This is tedious, error-prone, and does not scale\r\n% well.\r\n%%\r\n% You could also use the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/zeros.html |zeros|>\r\n% function with the final |classname| argument.  This works for\r\n% builtin numeric types.\r\nvalsaved = zeros(1,1,class(mu16));\r\n%%\r\n% Another method that also works for builtin types is using the function\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/cast.html |cast|>.\r\nb = cast(0.0,class(mu16));\r\n%% \r\n% What do we do if we have an input that behaves like a builtin numeric\r\n% clas but isn't built in?  Some examples might be the \r\n% <https:\/\/www.mathworks.com\/help\/symbolic\/sym.html |sym|>\r\n% object in the Symbolic Math Toolbox (assuming the variable contains values that can be converted to numeric ones) or the\r\n% <https:\/\/www.mathworks.com\/help\/fixedpoint\/ref\/fi.html |fi|> \r\n% fixed-point object from the Fixed-Point Toolbox.\r\nmsym = sym(md);\r\nmfi = fi(md);\r\nwhos\r\n%%\r\n% Here's a way to convert to an arbitrary class, using \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/str2func.html |str2func|>\r\nfhsym = str2func(class(msym));\r\nzsym = fhsym(0.0);\r\nfhfi = str2func(class(mfi));\r\nzfi = fhfi(0.0);\r\nwhos\r\n%%\r\n% There is a limitation to this method for Simulink users who want to use\r\n% embedded MATLAB in the generated code since |str2func| is not supported\r\n% for that situation.\r\n%% Methods that Should (Usually) Work for All Types\r\n% So, how to get that initial value to 0 in the right class?  Do some\r\n% arithmetic!  Here are two possibilites, illustrated with the |sym|\r\n% variable |msym|.\r\nzsym2 = 0*msym(1);\r\nzsym3 = msym(1)-msym(1);\r\n%%\r\n% Why do I say \"usually\" in the title of this section?  The calculations\r\n% should be supported for classes that behave numerically.\r\n%\r\n% Well, first, it allows me to refer you to a great numerical computing\r\n% reference.\r\n%\r\n% * Numerical Methods that [Usually] Work, Forman S. Acton, Harper & Row, Publishers,\r\n% ISBN 0883854503 (first published in 1970.  On my copy the words on the\r\n% cover are embossed in gold ink, except the word \"usually\" which is simply\r\n% impressed.\r\n%\r\n% Second, I have to admit that these methods only work for finite values of\r\n% the first input.  What would you do if you had to guard against\r\n% non-finite values?\r\n\r\n%% Other Methods or Preferences\r\n% Do you have other methods that would work for the conversion to an\r\n% unknown class?  Or preferences on a method to use?  If so, please \r\n% <?p=72#respond post here>.\r\n##### SOURCE END ##### 79cfe78b3d0245d7a73be9064f871d15\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      A while ago, I wrote an article sharing some ideas for Programming for Multiple Datatypes. Recently, a colleague asked me a related question for writing some M-code to be used in an... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/01\/05\/class-initialization-for-variables\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,15,11],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/72"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=72"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/72\/revisions"}],"predecessor-version":[{"id":2356,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/72\/revisions\/2356"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=72"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=72"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=72"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}