{"id":1274,"date":"2015-12-07T11:22:50","date_gmt":"2015-12-07T16:22:50","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=1274"},"modified":"2015-11-06T11:24:14","modified_gmt":"2015-11-06T16:24:14","slug":"no-infs-nans-or-bits","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2015\/12\/07\/no-infs-nans-or-bits\/","title":{"rendered":"No Infs, NaNs, or Bits"},"content":{"rendered":"\r\n<div class=\"content\"><!--introduction--><p>You may have heard the phrase \"no ifs, ands, or buts\" - meaning that there whatever the issue is, there is a definitive, non-negotiable answer or outcome.  I heard it often when trying to persuade my parents to allow me to do something they didn't want me to do.  Today when I heard someone use that phrase, what I sort of heard instead was \"no |Inf|s, |NaN|s, or bits\".  So I will talk about those values and types today.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#41a4f64b-296d-42b3-8590-b623756c9085\">Talking about infinity<\/a><\/li><li><a href=\"#dc032f15-ea11-4346-9378-bd61efc81d2b\">And now for the NaNs<\/a><\/li><li><a href=\"#dbf4d3e4-0b09-4451-b4f6-b2c1c307fd70\">Bits<\/a><\/li><li><a href=\"#8a8df2d1-539a-41b0-a3f8-23e0cba5f655\">Casting for an answer<\/a><\/li><li><a href=\"#a4cff4ba-397e-4b5f-a9b6-09e6dcebbd5f\">My bet...<\/a><\/li><\/ul><\/div><h4>Talking about infinity<a name=\"41a4f64b-296d-42b3-8590-b623756c9085\"><\/a><\/h4><p>In many applications, an infinite result is not acceptable.  I <b>do<\/b> remember a quantum physics final exam question where I did end up with <tt>Inf<\/tt>, but then realized I needed to take the arctangent (<tt>atan2<\/tt>), and all was good with my answer.  How do we detect the presence of infinity? Using one of the many <tt>is*<\/tt> functions!<\/p><p>Let me throw a bunch of values into an array so we can check them for various values or conditions.<\/p><pre class=\"codeinput\">vals = [-Inf 0 pi 17 42 Inf NaN]\r\n<\/pre><pre class=\"codeoutput\">vals =\r\n      -Inf         0    3.1416   17.0000   42.0000       Inf       NaN\r\n<\/pre><p>Notice that <tt>isinf<\/tt> correctly finds positive and negative infinite values.  First I see which ones are infinite, then I select them for display, via logical indexing.<\/p><pre class=\"codeinput\">nonInfVals = isinf(vals)\r\nmyInfVals = vals(nonInfVals)\r\n<\/pre><pre class=\"codeoutput\">nonInfVals =\r\n     1     0     0     0     0     1     0\r\nmyInfVals =\r\n  -Inf   Inf\r\n<\/pre><p>Instead, I can just find the finite values.<\/p><pre class=\"codeinput\">finiteVals = vals(isfinite(vals))\r\n<\/pre><pre class=\"codeoutput\">finiteVals =\r\n         0    3.1416   17.0000   42.0000\r\n<\/pre><p>For a nice use of <tt>-Inf<\/tt> in an algorithm, check out <a href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/08\/21\/finding-the-closest-value-less-than-a-threshold\/\">this post<\/a>, where a <tt>-Inf<\/tt> results indicate that no solution smaller than the threshold is available.<\/p><h4>And now for the NaNs<a name=\"dc032f15-ea11-4346-9378-bd61efc81d2b\"><\/a><\/h4><p>And, of course, there's my longstanding friend <tt>isnan<\/tt>, a great tool for selecting the <tt>NaN<\/tt> values, and along with logical indexing, replacing or removing them.<\/p><pre class=\"codeinput\">replacedNaNvals = vals;\r\nreplacedNaNvals(isnan(replacedNaNvals)) = -999\r\n<\/pre><pre class=\"codeoutput\">replacedNaNvals =\r\n      -Inf         0    3.1416   17.0000   42.0000       Inf -999.0000\r\n<\/pre><h4>Bits<a name=\"dbf4d3e4-0b09-4451-b4f6-b2c1c307fd70\"><\/a><\/h4><p>MATLAB does have <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/bit-wise-operations.html\">some functions for operating on arrays bit-wise<\/a>, but does not have a bit datatype.<\/p><p>While MATLAB doesn't have a bit datatype, it does have some integer types.  Let's see how we might use this.  I will create a cell array with different types in each cell so we can explore a bunch of types in one call.<\/p><pre class=\"codeinput\">mycell = {magic(2) uint8(magic(2)) <span class=\"string\">'buts'<\/span>; <span class=\"keyword\">...<\/span>\r\n    int32(magic(3)) [Inf -Inf] NaN; <span class=\"keyword\">...<\/span>\r\n    logical(eye(2)) {magic(2)} {uint8(magic(2))}}\r\n<\/pre><pre class=\"codeoutput\">mycell = \r\n    [2x2 double ]    [2x2 uint8 ]    'buts'    \r\n    [3x3 int32  ]    [1x2 double]    [     NaN]\r\n    [2x2 logical]    {1x1 cell  }    {1x1 cell}\r\n<\/pre><p>Let's see what <tt>isinteger<\/tt> can tell us.<\/p><pre class=\"codeinput\">integerCells = cellfun(@isinteger, mycell)\r\n<\/pre><pre class=\"codeoutput\">integerCells =\r\n     0     1     0\r\n     1     0     0\r\n     0     0     0\r\n<\/pre><p>Notice that this function, <tt>isinteger<\/tt>, essentially works on each separate array, rather than elementwise, because it is answering a question about the type of the array, not individual values.  Some <tt>is*<\/tt> functions act elementwise, and others act on an array as a whole.<\/p><h4>Casting for an answer<a name=\"8a8df2d1-539a-41b0-a3f8-23e0cba5f655\"><\/a><\/h4><p>There are a few more interesting functions in the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/numeric-types.html\">functions covering numeric types<\/a>, particularly, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/ref\/typecast.html\"><tt>typecast<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/ref\/cast.html\"><tt>cast<\/tt><\/a>.  <tt>typecast<\/tt> allows you to convert data types without changing the underlying data.  <tt>cast<\/tt> lets you cast the variable to a different datatype.  And <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/ref\/swapbytes.html\"><tt>swapbytes<\/tt><\/a> let's you swap the byte ordering, particularly useful for transforming the endianness of data.<\/p><h4>My bet...<a name=\"a4cff4ba-397e-4b5f-a9b6-09e6dcebbd5f\"><\/a><\/h4><p>No ifs ands or buts - I am sure many of you already make good use of a few of these Infs, NaNs, and bit functions.  What kind of data value wrangling do you do with MATLAB?  I mean things like I've mentioned in this post, not as \"big\" as peak or outlier detection.  MATLAB and add-on products do have many of those capabilities.  I'm looking for the \"little\" things.  Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=1274#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_a710cbefbf364275bd95792cb52178c7() {\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='a710cbefbf364275bd95792cb52178c7 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' a710cbefbf364275bd95792cb52178c7';\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        copyright = 'Copyright 2015 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 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');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\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_a710cbefbf364275bd95792cb52178c7()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2015b<br><\/p><\/div><!--\r\na710cbefbf364275bd95792cb52178c7 ##### SOURCE BEGIN #####\r\n%% No Infs, NaNs, or Bits\r\n% You may have heard the phrase \"no ifs, ands, or buts\" - meaning that\r\n% there whatever the issue is, there is a definitive, non-negotiable answer\r\n% or outcome.  I heard it often when trying to persuade my parents to allow\r\n% me to do something they didn't want me to do.  Today when I heard someone\r\n% use that phrase, what I sort of heard instead was \"no |Inf|s, |NaN|s, or\r\n% bits\".  So I will talk about those values and types today.\r\n\r\n%% Talking about infinity\r\n% In many applications, an infinite result is not acceptable.  I *do*\r\n% remember a quantum physics final exam question where I did end up with\r\n% |Inf|, but then realized I needed to take the arctangent (|atan2|), and\r\n% all was good with my answer.  How do we detect the presence of infinity?\r\n% Using one of the many |is*| functions!\r\n%%\r\n% Let me throw a bunch of values into an array so we can check them for\r\n% various values or conditions.\r\nvals = [-Inf 0 pi 17 42 Inf NaN]\r\n%%\r\n% Notice that |isinf| correctly finds positive and negative infinite\r\n% values.  First I see which ones are infinite, then I select them for\r\n% display, via logical indexing.\r\nnonInfVals = isinf(vals)\r\nmyInfVals = vals(nonInfVals)\r\n%%\r\n% Instead, I can just find the finite values.  \r\nfiniteVals = vals(isfinite(vals))\r\n\r\n%% \r\n% For a nice use of |-Inf| in an algorithm, check out\r\n% <https:\/\/blogs.mathworks.com\/loren\/2015\/08\/21\/finding-the-closest-value-less-than-a-threshold\/\r\n% this post>, where a |-Inf| results indicate that no solution smaller than\r\n% the threshold is available.\r\n\r\n%% And now for the NaNs\r\n% And, of course, there's my longstanding friend |isnan|, a great tool for\r\n% selecting the |NaN| values, and along with logical indexing, replacing or\r\n% removing them.\r\nreplacedNaNvals = vals;\r\nreplacedNaNvals(isnan(replacedNaNvals)) = -999\r\n\r\n%% Bits\r\n% MATLAB does have\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/bit-wise-operations.html\r\n% some functions for operating on arrays bit-wise>, but does not have a bit\r\n% datatype.\r\n\r\n%%\r\n% While MATLAB doesn't have a bit datatype, it does have some integer\r\n% types.  Let's see how we might use this.  I will create a cell array with\r\n% different types in each cell so we can explore a bunch of types in one\r\n% call.\r\nmycell = {magic(2) uint8(magic(2)) 'buts'; ...\r\n    int32(magic(3)) [Inf -Inf] NaN; ...\r\n    logical(eye(2)) {magic(2)} {uint8(magic(2))}}\r\n%%\r\n% Let's see what |isinteger| can tell us.\r\nintegerCells = cellfun(@isinteger, mycell)\r\n\r\n%% \r\n% Notice that this function, |isinteger|, essentially works on each\r\n% separate array, rather than elementwise, because it is answering a\r\n% question about the type of the array, not individual values.  Some |is*|\r\n% functions act elementwise, and others act on an array as a whole. \r\n\r\n%% Casting for an answer\r\n% There are a few more interesting functions in the\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/numeric-types.html\r\n% functions covering numeric types>, particularly,\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/ref\/typecast.html\r\n% |typecast|> and\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/ref\/cast.html\r\n% |cast|>.  |typecast| allows you to convert data types without changing\r\n% the underlying data.  |cast| lets you cast the variable to a different\r\n% datatype.  And <https:\/\/www.mathworks.com\/help\/releases\/R2015b\/matlab\/ref\/swapbytes.html\r\n% |swapbytes|> let's you swap the byte ordering, particularly useful for\r\n% transforming the endianness of data.\r\n\r\n%% My bet...\r\n% No ifs ands or buts - I am sure many of you already make good use of a\r\n% few of these Infs, NaNs, and bit functions.  What kind of data value\r\n% wrangling do you do with MATLAB?  I mean things like I've mentioned in\r\n% this post, not as \"big\" as peak or outlier detection.  MATLAB and add-on\r\n% products do have many of those capabilities.  I'm looking for the\r\n% \"little\" things.  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=1274#respond here>.\r\n\r\n\r\n\r\n\r\n\r\n##### SOURCE END ##### a710cbefbf364275bd95792cb52178c7\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>You may have heard the phrase \"no ifs, ands, or buts\" - meaning that there whatever the issue is, there is a definitive, non-negotiable answer or outcome.  I heard it often when trying to persuade my parents to allow me to do something they didn't want me to do.  Today when I heard someone use that phrase, what I sort of heard instead was \"no |Inf|s, |NaN|s, or bits\".  So I will talk about those values and types today.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/12\/07\/no-infs-nans-or-bits\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,39],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1274"}],"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=1274"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1274\/revisions"}],"predecessor-version":[{"id":1275,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1274\/revisions\/1275"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=1274"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=1274"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=1274"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}