{"id":1213,"date":"2015-08-21T07:41:08","date_gmt":"2015-08-21T12:41:08","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=1213"},"modified":"2015-08-21T12:53:36","modified_gmt":"2015-08-21T17:53:36","slug":"finding-the-closest-value-less-than-a-threshold","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2015\/08\/21\/finding-the-closest-value-less-than-a-threshold\/","title":{"rendered":"Finding the Closest Value Less than a Threshold"},"content":{"rendered":"<div class=\"content\"><!--introduction--><p>I just got asked a question about a good way to find the closest value in a vector that was less than a threshold. My solution is fairly short, and demonstrates some of my favorite MATLAB techniques.  I will compare also show you an \"obvious\" solution.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#1d908cc9-dbae-4175-a99e-6b1b799c2a64\">Set up<\/a><\/li><li><a href=\"#fbfdbfc6-09b5-49c3-a37f-61330315449b\">Solution via looping<\/a><\/li><li><a href=\"#8d18e2f7-7127-4673-901c-158a156237aa\">Solution using logical indexing<\/a><\/li><li><a href=\"#91adb070-14c7-49f1-b3da-2a26e3f3ae85\">Let's make sure both solutions match<\/a><\/li><li><a href=\"#9adca9fb-a346-4923-9777-8d85580c5b02\">Which solution do you prefer?<\/a><\/li><\/ul><\/div><h4>Set up<a name=\"1d908cc9-dbae-4175-a99e-6b1b799c2a64\"><\/a><\/h4><p>First let's set up the data for our problem.<\/p><pre class=\"codeinput\">thresh = 75;\r\nnvals = 10^6;\r\ndata = 100*rand(1,nvals);\r\n<\/pre><h4>Solution via looping<a name=\"fbfdbfc6-09b5-49c3-a37f-61330315449b\"><\/a><\/h4><p>We could solve this by brute force, just looping over the values.  Let's try that.  I'm going to set the index value to empty (<tt>[]<\/tt>).  That way, if we end up with an array that doesn't meet the criterion, we can tell. Also, I am setting the current minimum value to <tt>-Inf<\/tt> so any finite value that we find as a valid candidate will be closer to <tt>thresh<\/tt>, assuming we can find one.<\/p><pre class=\"codeinput\">loopindex = [];\r\ncandidate = -inf;\r\n<span class=\"keyword\">for<\/span> ind = 1:numel(data)\r\n    dval = data(ind);\r\n    <span class=\"keyword\">if<\/span> dval &lt; thresh &amp;&amp; dval &gt; candidate\r\n        candidate = dval;\r\n        loopindex = ind;\r\n    <span class=\"keyword\">end<\/span>\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><h4>Solution using logical indexing<a name=\"8d18e2f7-7127-4673-901c-158a156237aa\"><\/a><\/h4><p>Next I show you my non-loop solution.<\/p><p>First collect the list of possible data entries - the ones that are less than the threshold value <tt>thresh<\/tt>. This list is a logical variable, essentially true and false values for each entry in <tt>data<\/tt>, selecting the candidate values that are less than the <tt>thresh<\/tt> value.<\/p><pre class=\"codeinput\">possibles = data &lt; thresh;\r\n<\/pre><p>Let's find the actual best value, plus its index into the reduced set from <tt>possibles<\/tt>.  The index we find will not be the index into <tt>data<\/tt> but rather into a smaller array which is the subset meeting the threshold criteria.<\/p><pre class=\"codeinput\">[posmax, posind] = max(data(possibles));\r\n<\/pre><p>Convert the answer into the correct index in the <i>original<\/i> array, <tt>data<\/tt>.<\/p><pre class=\"codeinput\">inddatapos = find(possibles); <span class=\"comment\">% possible indices<\/span>\r\ninddata = inddatapos(posind); <span class=\"comment\">% find the index we care about<\/span>\r\n<\/pre><p>If <tt>inddata<\/tt> is empty, then there were no possible values meeting the criterion.  So we set the final values accordingly.<\/p><pre class=\"codeinput\"><span class=\"keyword\">if<\/span> isempty(inddata)\r\n    posmax = -Inf;\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><h4>Let's make sure both solutions match<a name=\"91adb070-14c7-49f1-b3da-2a26e3f3ae85\"><\/a><\/h4><pre class=\"codeinput\">sameSolution = isequal([inddata posmax],[loopindex candidate])\r\n<\/pre><pre class=\"codeoutput\">sameSolution =\r\n     1\r\n<\/pre><h4>Which solution do you prefer?<a name=\"9adca9fb-a346-4923-9777-8d85580c5b02\"><\/a><\/h4><p>You might guess correctly which solution is more natural to me at this point :-). I am wondering which solution you prefer, and why? Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=1213#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_ba8ce2b06f314a84b95e45310b633417() {\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='ba8ce2b06f314a84b95e45310b633417 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' ba8ce2b06f314a84b95e45310b633417';\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_ba8ce2b06f314a84b95e45310b633417()\"><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; R2015a<br><\/p><\/div><!--\r\nba8ce2b06f314a84b95e45310b633417 ##### SOURCE BEGIN #####\r\n%% Finding the Closest Value Less than a Threshold\r\n% I just got asked a question about a good way to find the closest value in\r\n% a vector that was less than a threshold. My solution is fairly short,\r\n% and demonstrates some of my favorite MATLAB techniques.  I will compare\r\n% also show you an \"obvious\" solution.\r\n%% Set up\r\n% First let's set up the data for our problem.\r\nthresh = 75;\r\nnvals = 10^6;\r\ndata = 100*rand(1,nvals);\r\n%% Solution via looping\r\n% We could solve this by brute force, just looping over the values.  Let's\r\n% try that.  I'm going to set the index value to empty (|[]|).  That way,\r\n% if we end up with an array that doesn't meet the criterion, we can tell.\r\n% Also, I am setting the current minimum value to |-Inf| so any finite\r\n% value that we find as a valid candidate will be closer to |thresh|,\r\n% assuming we can find one.\r\nloopindex = [];\r\ncandidate = -inf;\r\nfor ind = 1:numel(data)\r\n    dval = data(ind);\r\n    if dval < thresh && dval > candidate\r\n        candidate = dval;\r\n        loopindex = ind;\r\n    end\r\nend\r\n%% Solution using logical indexing\r\n% Next I show you my non-loop solution.\r\n%%\r\n% First collect the list of possible data entries - the ones that are less\r\n% than the threshold value |thresh|.\r\n% This list is a logical variable, essentially true and false values for\r\n% each entry in |data|, selecting the candidate values that are less than\r\n% the |thresh| value.\r\npossibles = data < thresh;\r\n%% \r\n% Let's find the actual best value, plus its index into the reduced set\r\n% from |possibles|.  The index we find will not be the index into\r\n% |data| but rather into a smaller array which is the subset meeting\r\n% the threshold criteria.\r\n[posmax, posind] = max(data(possibles));\r\n%%\r\n% Convert the answer into the correct index in the _original_ array,\r\n% |data|.\r\ninddatapos = find(possibles); % possible indices\r\ninddata = inddatapos(posind); % find the index we care about\r\n%% \r\n% If |inddata| is empty, then there were no possible values meeting the\r\n% criterion.  So we set the final values accordingly.\r\nif isempty(inddata)\r\n    posmax = -Inf;\r\nend\r\n%% Let's make sure both solutions match\r\nsameSolution = isequal([inddata posmax],[loopindex candidate])\r\n%% Which solution do you prefer?\r\n% You might guess correctly which solution is more natural to me at this\r\n% point :-). I am wondering which solution you prefer, and why? Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=1213#respond here>.\r\n\r\n\r\n    \r\n\r\n\r\n##### SOURCE END ##### ba8ce2b06f314a84b95e45310b633417\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>I just got asked a question about a good way to find the closest value in a vector that was less than a threshold. My solution is fairly short, and demonstrates some of my favorite MATLAB techniques.  I will compare also show you an \"obvious\" solution.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/08\/21\/finding-the-closest-value-less-than-a-threshold\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[4,12],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1213"}],"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=1213"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1213\/revisions"}],"predecessor-version":[{"id":1214,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1213\/revisions\/1214"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=1213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=1213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=1213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}