{"id":637,"date":"2013-02-20T08:48:52","date_gmt":"2013-02-20T13:48:52","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=637"},"modified":"2013-02-21T08:43:15","modified_gmt":"2013-02-21T13:43:15","slug":"logical-indexing-multiple-conditions","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2013\/02\/20\/logical-indexing-multiple-conditions\/","title":{"rendered":"Logical Indexing &#8211; Multiple Conditions"},"content":{"rendered":"<!DOCTYPE html\r\n  PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN\">\r\n<style type=\"text\/css\">\r\n\r\nh1 { font-size:18pt; }\r\nh2.titlebg { font-size:13pt; }\r\nh3 { color:#4A4F55; padding:0px; margin:5px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:11pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\nh4 { color:#4A4F55; padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:10pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\n   \r\np { padding:0px; margin:0px 0px 20px; }\r\nimg { padding:0px; margin:0px 0px 20px; border:none; }\r\np img, pre img, tt img, li img { margin-bottom:0px; } \r\n\r\nul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }\r\nul li { padding:0px; margin:0px 0px 7px 0px; background:none; }\r\nul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }\r\nul li ol li { list-style:decimal; }\r\nol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }\r\nol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }\r\nol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }\r\nol li ol li { list-style-type:lower-alpha; }\r\nol li ul { padding-top:7px; }\r\nol li ul li { list-style:square; }\r\n\r\npre, tt, code { font-size:12px; }\r\npre { margin:0px 0px 20px; }\r\npre.error { color:red; }\r\npre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }\r\npre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }\r\n\r\n@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }\r\n\r\nspan.keyword { color:#0000FF }\r\nspan.comment { color:#228B22 }\r\nspan.string { color:#A020F0 }\r\nspan.untermstring { color:#B20000 }\r\nspan.syscmd { color:#B28C00 }\r\n\r\n.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }\r\n.footer p { margin:0px; }\r\n\r\n  <\/style><div class=\"content\"><!--introduction--><p>I've talked about logical <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/\">indexing<\/a> before in some of the linked posts, but recent work makes me want to show it off again.  One of the nice things about logical indexing is that it is very easy and natural to combine the results of different conditions to select items based on multiple criteria.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#33f0748f-5b6e-4605-9d0d-a86827bdb8a3\">What is Logical Indexing?<\/a><\/li><li><a href=\"#ef412173-88ef-43d1-81ab-b2df3d7dde77\">Compound conditions.<\/a><\/li><li><a href=\"#f4e56162-08ec-44b0-a4e8-7086976be875\">Find Values Meeting More Than One Condition<\/a><\/li><li><a href=\"#a554527a-320f-40bd-95dc-42695925b486\">Did You Notice?<\/a><\/li><li><a href=\"#e9531c73-0182-4f21-8bf5-c11a0970562d\">A Recent Application<\/a><\/li><li><a href=\"#14ef4d77-81f6-4722-a6ce-3cd56ca4d31b\">Have You Used Compound Indexing?<\/a><\/li><\/ul><\/div><h4>What is Logical Indexing?<a name=\"33f0748f-5b6e-4605-9d0d-a86827bdb8a3\"><\/a><\/h4><p>Suppose I have an array of integers, not sorted, and want to find the ones that are less than a certain number.  Here's how I can do it using the function <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/find.html\"><tt>find<\/tt><\/a>.<\/p><pre class=\"codeinput\">X = randperm(20)\r\ntarget = 5;\r\n<\/pre><pre class=\"codeoutput\">X =\r\n  Columns 1 through 13\r\n     3     7     1    16    20    15    13     9    14     8    11    19    18\r\n  Columns 14 through 20\r\n     4    10     5     6    17    12     2\r\n<\/pre><pre class=\"codeinput\">ind = find(X &lt; target)\r\n<\/pre><pre class=\"codeoutput\">ind =\r\n     1     3    14    20\r\n<\/pre><p>You can see that find returns the indices into the array <tt>X<\/tt> that have values less than the <tt>target<\/tt>.  And we can use these to extract the values.<\/p><pre class=\"codeinput\">Xtarget = X(ind)\r\n<\/pre><pre class=\"codeoutput\">Xtarget =\r\n     3     1     4     2\r\n<\/pre><p>Another way to accomplish the same outcome is to use the logical expression to directly perform the indexing operation.  Here's what I mean.<\/p><pre class=\"codeinput\">logInd = X &lt; target\r\n<\/pre><pre class=\"codeoutput\">logInd =\r\n  Columns 1 through 13\r\n     1     0     1     0     0     0     0     0     0     0     0     0     0\r\n  Columns 14 through 20\r\n     1     0     0     0     0     0     1\r\n<\/pre><p>MATLAB returns an array that matches the elements of the array <tt>X<\/tt>, element-by-element holding 1s where the matching values in <tt>X<\/tt> are the desired values, and 0s otherwise.  The array <tt>logInd<\/tt> is not an array of double numbers, but have the class <tt>logical<\/tt>.<\/p><pre class=\"codeinput\">whos <span class=\"string\">logInd<\/span>\r\n<\/pre><pre class=\"codeoutput\">  Name        Size            Bytes  Class      Attributes\r\n\r\n  logInd      1x20               20  logical              \r\n\r\n<\/pre><p>I can now use this array to extract the desired values from <tt>X<\/tt>.<\/p><pre class=\"codeinput\">XtargetLogical = X(logInd)\r\n<\/pre><pre class=\"codeoutput\">XtargetLogical =\r\n     3     1     4     2\r\n<\/pre><p>Both methods return the results.<\/p><pre class=\"codeinput\">isequal(Xtarget, XtargetLogical)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     1\r\n<\/pre><h4>Compound conditions.<a name=\"ef412173-88ef-43d1-81ab-b2df3d7dde77\"><\/a><\/h4><p>Let me create an anonymous function that returns true (<tt>logical(1)<\/tt>) for values that are even integers.<\/p><pre class=\"codeinput\">iseven = @(x) ~logical(rem(x,2))\r\n<\/pre><pre class=\"codeoutput\">iseven = \r\n    @(x)~logical(rem(x,2))\r\n<\/pre><p>Test <tt>iseven<\/tt>.<\/p><pre class=\"codeinput\">iseven(1:5)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     0     1     0     1     0\r\n<\/pre><h4>Find Values Meeting More Than One Condition<a name=\"f4e56162-08ec-44b0-a4e8-7086976be875\"><\/a><\/h4><p>Now I would like to find the values in <tt>X<\/tt> that are less than <tt>target<\/tt> and are even. This is very natural to do with logical indexing.  We have the pieces of code we need already.<\/p><pre class=\"codeinput\">compoundCondInd = (X &lt; target) &amp; iseven(X)\r\n<\/pre><pre class=\"codeoutput\">compoundCondInd =\r\n  Columns 1 through 13\r\n     0     0     0     0     0     0     0     0     0     0     0     0     0\r\n  Columns 14 through 20\r\n     1     0     0     0     0     0     1\r\n<\/pre><p>We can see we found suitable values at locations 3 and 19.  And we can extract those values next.<\/p><pre class=\"codeinput\">X(compoundCondInd)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     4     2\r\n<\/pre><h4>Did You Notice?<a name=\"a554527a-320f-40bd-95dc-42695925b486\"><\/a><\/h4><p>Did you see how easy it is to combine multiple conditions?  I simply look for each of condition, getting back logical arrays, and then compute a logical array where the two input arrays are both true (via <tt>&amp;<\/tt>). I could, of course, calculate a compound condition where only either one or the other condition needs to be true using logical or (via |).<\/p><h4>A Recent Application<a name=\"e9531c73-0182-4f21-8bf5-c11a0970562d\"><\/a><\/h4><p>I recently used this in the context of finding suspect data values.  I had 2 arrays, hourly temperature and speed.  The problem is that when the temperature gets near or below freezing, the speed sensor might freeze. But I didn't want to delete ALL the values below freezing.  So I looked for data where the temperature was sufficiently low AND the speed was very low (which could potentially mean the sensor was frozen).  That way, I did not need to discard all data at low temperatures.<\/p><h4>Have You Used Compound Indexing?<a name=\"14ef4d77-81f6-4722-a6ce-3cd56ca4d31b\"><\/a><\/h4><p>Did you do it like I did, using logical expressions?  Or did you use some other techniques?  What were you trying to achieve with your compound indexing?  Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=637#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_bc94e2aee9fb45b9b09b65745fcb27fb() {\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='bc94e2aee9fb45b9b09b65745fcb27fb ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' bc94e2aee9fb45b9b09b65745fcb27fb';\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 2013 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_bc94e2aee9fb45b9b09b65745fcb27fb()\"><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; R2012b<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; R2012b<br><\/p><\/div><!--\r\nbc94e2aee9fb45b9b09b65745fcb27fb ##### SOURCE BEGIN #####\r\n%% Logical Indexing - Multiple Conditions\r\n% I've talked about logical\r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/ indexing> before in\r\n% some of the linked posts, but recent work makes me want to show it off\r\n% again.  One of the nice things about logical indexing is that it is very\r\n% easy and natural to combine the results of different conditions to select\r\n% items based on multiple criteria.\r\n%% What is Logical Indexing?\r\n% Suppose I have an array of integers, not sorted, and want to find the\r\n% ones that are less than a certain number.  Here's how I can do it using\r\n% the function <https:\/\/www.mathworks.com\/help\/matlab\/ref\/find.html |find|>.\r\nX = randperm(20)\r\ntarget = 5;\r\n%%\r\nind = find(X < target)\r\n%%\r\n% You can see that find returns the indices into the array |X| that have\r\n% values less than the |target|.  And we can use these to extract the\r\n% values.\r\nXtarget = X(ind)\r\n%%\r\n% Another way to accomplish the same outcome is to use the logical\r\n% expression to directly perform the indexing operation.  Here's what I\r\n% mean.\r\nlogInd = X < target\r\n%%\r\n% MATLAB returns an array that matches the elements of the array |X|,\r\n% element-by-element holding 1s where the matching values in |X| are the\r\n% desired values, and 0s otherwise.  The array |logInd| is not an array of\r\n% double numbers, but have the class |logical|.\r\nwhos logInd\r\n%%\r\n% I can now use this array to extract the desired values from |X|.\r\nXtargetLogical = X(logInd)\r\n%%\r\n% Both methods return the results.\r\nisequal(Xtarget, XtargetLogical)\r\n%% Compound conditions.\r\n% Let me create an anonymous function that returns true (|logical(1)|) for\r\n% values that are even integers.\r\niseven = @(x) ~logical(rem(x,2))\r\n%%\r\n% Test |iseven|.\r\niseven(1:5)\r\n%% Find Values Meeting More Than One Condition\r\n% Now I would like to find the values in |X| that are less than |target|\r\n% and are even. This is very natural to do with logical indexing.  We have\r\n% the pieces of code we need already.\r\ncompoundCondInd = (X < target) & iseven(X)\r\n%%\r\n% We can see we found suitable values at locations 3 and 19.  And we can\r\n% extract those values next.\r\nX(compoundCondInd)\r\n%%  Did You Notice?\r\n% Did you see how easy it is to combine multiple conditions?  I simply look\r\n% for each of condition, getting back logical arrays, and then compute a\r\n% logical array where the two input arrays are both true (via |&|). I\r\n% could, of course, calculate a compound condition where only either one or\r\n% the other condition needs to be true using logical or (via |||).\r\n%% A Recent Application\r\n% I recently used this in the context of finding suspect data values.  I\r\n% had 2 arrays, hourly temperature and speed.  The problem is that when the\r\n% temperature gets near or below freezing, the speed sensor might freeze.\r\n% But I didn't want to delete ALL the values below freezing.  So I looked\r\n% for data where the temperature was sufficiently low AND the speed was\r\n% very low (which could potentially mean the sensor was frozen).  That way,\r\n% I did not need to discard all data at low temperatures.\r\n%% Have You Used Compound Indexing?\r\n% Did you do it like I did, using logical expressions?  Or did you use some\r\n% other techniques?  What were you trying to achieve with your compound\r\n% indexing?  Let me know <https:\/\/blogs.mathworks.com\/loren\/?p=637#respond\r\n% here>.\r\n\r\n##### SOURCE END ##### bc94e2aee9fb45b9b09b65745fcb27fb\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>I've talked about logical <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/\">indexing<\/a> before in some of the linked posts, but recent work makes me want to show it off again.  One of the nice things about logical indexing is that it is very easy and natural to combine the results of different conditions to select items based on multiple criteria.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2013\/02\/20\/logical-indexing-multiple-conditions\/\">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],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/637"}],"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=637"}],"version-history":[{"count":5,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/637\/revisions"}],"predecessor-version":[{"id":642,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/637\/revisions\/642"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=637"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=637"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=637"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}