{"id":218,"date":"2010-02-17T18:51:32","date_gmt":"2010-02-17T18:51:32","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2010\/02\/17\/ensuring-positive-values-part-1\/"},"modified":"2010-02-17T18:51:51","modified_gmt":"2010-02-17T18:51:51","slug":"ensuring-positive-values-part-1","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2010\/02\/17\/ensuring-positive-values-part-1\/","title":{"rendered":"Ensuring Positive Values &#8211; Part 1"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Do you sometimes need to be sure an array has only bounded, positive values?  At least one customer asked about this recently\r\n         and noted that it could be quite involved.  Depending on the duration for which you need to ensure this, there is more than\r\n         one way to attack this.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Possible Scenarios<\/a><\/li>\r\n         <li><a href=\"#2\">Point Checks<\/a><\/li>\r\n         <li><a href=\"#3\">Method 1 - Manual Checking<\/a><\/li>\r\n         <li><a href=\"#4\">Method 2 - Make an Assertion<\/a><\/li>\r\n         <li><a href=\"#5\">Method 3 - Validate the Array<\/a><\/li>\r\n         <li><a href=\"#6\">Interesting Functions to Consider<\/a><\/li>\r\n         <li><a href=\"#7\">Stayed Tuned...<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Possible Scenarios<a name=\"1\"><\/a><\/h3>\r\n   <p>Here are the two main scenarios I can think of.<\/p>\r\n   <li>Check that values are all in range only at certain points in a calculation.<\/li>\r\n   <li>Ensure that values are <b>always<\/b> in range throughout their lifetime.\r\n   <\/li>\r\n   <p>I would be tempted to attack these scenarios in different ways.  This week, I'll cover the first scenario.<\/p>\r\n   <h3>Point Checks<a name=\"2\"><\/a><\/h3>\r\n   <p>If I were only going to check once in a while, I might write some code using some simple MATLAB functions and check details\r\n      methodically.\r\n   <\/p>\r\n   <h3>Method 1 - Manual Checking<a name=\"3\"><\/a><\/h3>\r\n   <p>The first method would try to test every assumption I can think of, perhaps like this:<\/p><pre>    ispositive = ( ~isnumeric(x) ...\r\n                 | ~all(isfinite(x(:))) ...\r\n                 | ~isreal(x) ...\r\n                 | ~(any(x(:) &lt;= 0)));\r\n    if ~ispositive\r\n       doSomething(perhaps, throw, anError);\r\n    end<\/pre><p>There are some possible gotchas with this. There is a long of list of <tt>is*<\/tt> functions.  Which ones do we need to consider?  For example, old-style graphics handles are stored as doubles so they could\r\n      confuse the results.\r\n   <\/p>\r\n   <h3>Method 2 - Make an Assertion<a name=\"4\"><\/a><\/h3>\r\n   <p>I can embed these checks into an assertion at places in my code where I want to be sure the data is correct.  To not have\r\n      to recreate the logic everytime, I can construct a function handle (anonymous in this case) and use it when I make each assertion.\r\n   <\/p><pre>    fhispositive = @(x) ( ~isnumeric(x) ...\r\n                 | ~all(isfinite(x(:))) ...\r\n                 | ~isreal(x) ...\r\n                 | ~(any(x(:) &lt;= 0)));\r\n    assert(fhispositive(x), ...\r\n          'myapp:checkData:notPos', ...\r\n          'Data not all positive.');<\/pre><p>I am now free to reuse the function handle with <tt>assert<\/tt> in strategic places throughout the code, not just at the one place where I typed the original code.\r\n   <\/p>\r\n   <p><b>Note:<\/b> you can do this as well by creating a separate function (in a separate file or a subfunction) to do the checking.  Additionally,\r\n      <tt>assert<\/tt> is only one possible behavior for the case where the data don't comply with the assumptions. You could instead set the data\r\n      to a default value, for example.\r\n   <\/p>\r\n   <h3>Method 3 - Validate the Array<a name=\"5\"><\/a><\/h3>\r\n   <p>In a MATLAB release R2007b, you'll find the function <tt>validateattributes<\/tt> (as well as <tt>validatestring<\/tt>).  Using <tt>validateattributes<\/tt>, you can more compactly check data properties.  You will get an error if the data doesn't match the requirements.\r\n   <\/p><pre>    validateattributes(x,{'numeric'},...\r\n                 {'finite','positive'});<\/pre><h3>Interesting Functions to Consider<a name=\"6\"><\/a><\/h3>\r\n   <p>Here's a list of interesting functions to consider helping you with such checks including the <tt>is*<\/tt> functions mentioned above.\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/is.html\"><tt>is*<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/inputparser.html\"><tt>inputParser<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/assert.html\"><tt>assert<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/validateattributes.html\"><tt>validateattributes<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/isfinite.html\"><tt>isfinite<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/f16-6011.html#bq1labr-1\">relational and logical operators<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Stayed Tuned...<a name=\"7\"><\/a><\/h3>\r\n   <p>Stay tuned for a demo of a solution to the second scenario where you always want to ensure that the data is in a valid state.\r\n       In the meantime, I'd love to hear if you have requirements or constraints where controlling the values in an array are important.\r\n       Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=218\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_26b60738329e4463a0fb1d1302b2174c() {\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='26b60738329e4463a0fb1d1302b2174c ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 26b60738329e4463a0fb1d1302b2174c';\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 2010 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_26b60738329e4463a0fb1d1302b2174c()\"><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.9<br><\/p>\r\n<\/div>\r\n<!--\r\n26b60738329e4463a0fb1d1302b2174c ##### SOURCE BEGIN #####\r\n%% Ensuring Positive Values - Part 1\r\n% Do you sometimes need to be sure an array has only bounded, positive\r\n% values?  At least one customer asked about this recently and noted that\r\n% it could be quite involved.  Depending on the duration for which you need\r\n% to ensure this, there is more than one way to attack this.\r\n%% Possible Scenarios\r\n% Here are the two main scenarios I can think of.\r\n%\r\n% # Check that values are all in range only at certain points in a\r\n% calculation.  \r\n% # Ensure that values are *always* in range throughout their lifetime.\r\n%\r\n% I would be tempted to attack these scenarios in different ways.  This\r\n% week, I'll cover the first scenario.\r\n%\r\n%% Point Checks\r\n% If I were only going to check once in a while, I might write some code\r\n% using some simple MATLAB functions and check details methodically.\r\n%\r\n%% Method 1 - Manual Checking\r\n% The first method would try to test every assumption I can think of,\r\n% perhaps like this:\r\n%\r\n%      ispositive = ( ~isnumeric(x) ...\r\n%                   | ~all(isfinite(x(:))) ...\r\n%                   | ~isreal(x) ...\r\n%                   | ~(any(x(:) <= 0)));\r\n%      if ~ispositive\r\n%         doSomething(perhaps, throw, anError);\r\n%      end\r\n%\r\n% There are some possible gotchas with this.  \r\n% There is a long of list of |is*|\r\n% functions.  Which ones do we need to consider?  For example, old-style \r\n% graphics handles are stored as doubles so they could confuse the results.\r\n\r\n%% Method 2 - Make an Assertion\r\n% I can embed these checks into an assertion at places in my code where I\r\n% want to be sure the data is correct.  To not have to recreate the logic\r\n% everytime, I can construct a function handle (anonymous in this case) and\r\n% use it when I make each assertion.\r\n%\r\n%      fhispositive = @(x) ( ~isnumeric(x) ...\r\n%                   | ~all(isfinite(x(:))) ...\r\n%                   | ~isreal(x) ...\r\n%                   | ~(any(x(:) <= 0)));\r\n%      assert(fhispositive(x), ...\r\n%            'myapp:checkData:notPos', ...\r\n%            'Data not all positive.'); \r\n%\r\n% I am now free to reuse the function handle with |assert| in strategic\r\n% places throughout the code, not just at the one place where I typed the\r\n% original code.  \r\n%\r\n% *Note:* you can do this as well by creating a separate function (in a\r\n% separate file or a subfunction) to do the checking.  Additionally,\r\n% |assert| is only one possible behavior for the case where the data don't\r\n% comply with the assumptions. You could instead set the data to a default\r\n% value, for example.\r\n\r\n%% Method 3 - Validate the Array\r\n% In a MATLAB release R2007b, you'll find the function |validateattributes|\r\n% (as well as |validatestring|).  Using |validateattributes|, you can more\r\n% compactly check data properties.  You will get an error if the data\r\n% doesn't match the requirements.\r\n%\r\n%      validateattributes(x,{'numeric'},...\r\n%                   {'finite','positive'});\r\n%\r\n%% Interesting Functions to Consider\r\n% Here's a list of interesting functions to consider helping you with such\r\n% checks including the |is*| functions mentioned above.\r\n%\r\n% * <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/is.html |is*|>\r\n% * <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/inputparser.html |inputParser|>\r\n% * <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/assert.html |assert|>\r\n% * <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/validateattributes.html |validateattributes|>\r\n% * <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/isfinite.html |isfinite|>\r\n% * <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/f16-6011.html#bq1labr-1 relational and logical operators>\r\n%\r\n%% Stayed Tuned...\r\n% Stay tuned for a demo of a solution to the second scenario where you\r\n% always want to ensure that the data is in a valid state.  In the\r\n% meantime, I'd love to hear if you have requirements or constraints where\r\n% controlling the values in an array are important.  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=218 here>.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n##### SOURCE END ##### 26b60738329e4463a0fb1d1302b2174c\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Do you sometimes need to be sure an array has only bounded, positive values?  At least one customer asked about this recently\r\n         and noted that it could be quite involved. ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2010\/02\/17\/ensuring-positive-values-part-1\/\">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,6,11],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/218"}],"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=218"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/218\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=218"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=218"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=218"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}