{"id":249,"date":"2010-10-07T17:52:52","date_gmt":"2010-10-07T17:52:52","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2010\/10\/07\/indexing-mixing-it-up\/"},"modified":"2016-08-04T08:35:26","modified_gmt":"2016-08-04T13:35:26","slug":"indexing-mixing-it-up","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2010\/10\/07\/indexing-mixing-it-up\/","title":{"rendered":"Indexing &#8211; Mixing It Up"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I've written a bunch of posts related to <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/\">indexing<\/a>, but I still haven't showed all the flexibility allowed.  Today I'm going to add a variant to the list.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Types of Indexing - a Review<\/a><\/li>\r\n         <li><a href=\"#9\">Combining Styles of Indexing<\/a><\/li>\r\n         <li><a href=\"#13\">Combine Techniques<\/a><\/li>\r\n         <li><a href=\"#15\">Have You Combined Indexing Techniques?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Types of Indexing - a Review<a name=\"1\"><\/a><\/h3>\r\n   <p>Let's start with indexing using subscripts. Let's start by creating a matrix.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]<\/pre><pre style=\"font-style:oblique\">A =\r\n     1     2     3     4\r\n     5     6     7     8\r\n     9    10    11    12\r\n    13    14    15    16\r\n<\/pre><p>If I want to pick out the element sitting in the second row, third column, I simply write this<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">el23 = A(2,3)<\/pre><pre style=\"font-style:oblique\">el23 =\r\n     7\r\n<\/pre><p>and you see result 7.<\/p>\r\n   <p>If I want another element as well, let's say 4th row, 2nd element, I can certainly follow my last statement with a similar\r\n      one.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">el42 = A(4,2)<\/pre><pre style=\"font-style:oblique\">el42 =\r\n    14\r\n<\/pre><p>If I want both those elements extracted, I can try combining their respective row and column indices.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">els = A([2 4],[3 2])<\/pre><pre style=\"font-style:oblique\">els =\r\n     7     6\r\n    15    14\r\n<\/pre><p>What you see is that MATLAB returns the 4 intersections, not just the first row with the first column index, and same for\r\n      second.  Instead we get each row index combined with each column index.  To get only the two elements we originally sought,\r\n      we can convert the subscripts into another form of index, a linear index.  With linear indexing, we think of an array as starting\r\n      with the (1,1) element, and, going down each row, stringing out the elements into a long column.  Then we use the count into\r\n      that column vector, which has length equal to <tt>numRows * numCols<\/tt>. Use <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/sub2ind.html\"><tt>sub2ind<\/tt><\/a> to make the transformation.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">linInds = sub2ind(size(A),[2 4],[3,2])<\/pre><pre style=\"font-style:oblique\">linInds =\r\n    10     8\r\n<\/pre><p>and then use these to index back into <tt>A<\/tt>,\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(linInds)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     7    14\r\n<\/pre><p>getting exactly the values expected.<\/p>\r\n   <p>At least I hope they are the values you expected, instead of 10 and 8. Remember, MATLAB stores array values columnwise, i.e.,\r\n      column followed by column.\r\n   <\/p>\r\n   <h3>Combining Styles of Indexing<a name=\"9\"><\/a><\/h3>\r\n   <p>Now consider another situation, where you have a matrix and you only want certain columns extracted, depending on the value\r\n      in the corresponding row.  Perhaps, for example, you are using <tt>NaN<\/tt> as a placeholder and you only want columns 2 and 4 in rows that do <b>not<\/b> start with <tt>NaN<\/tt>.\r\n   <\/p>\r\n   <p>One function that will be useful to us here is <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/isnan.html\"><tt>isnan<\/tt><\/a>, and the output of <tt>isnan<\/tt> is a logical array (think <tt>true<\/tt> and <tt>false<\/tt>). If I have a vector D like this,\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">D = [ 1 NaN 3 -4 NaN pi]'<\/pre><pre style=\"font-style:oblique\">D =\r\n            1\r\n          NaN\r\n            3\r\n           -4\r\n          NaN\r\n       3.1416\r\n<\/pre><p>I can identify which entries have <tt>NaN<\/tt> values.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">nanD = isnan(D);\r\nwhos <span style=\"color: #A020F0\">nanD<\/span>\r\nnanD<\/pre><pre style=\"font-style:oblique\">  Name      Size            Bytes  Class      Attributes\r\n\r\n  nanD      6x1                 6  logical              \r\n\r\nnanD =\r\n     0\r\n     1\r\n     0\r\n     0\r\n     1\r\n     0\r\n<\/pre><p>I can us logical indexing to extract the non-|NaN| entries in <tt>D<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">nonNaND = D(~nanD)<\/pre><pre style=\"font-style:oblique\">nonNaND =\r\n            1\r\n            3\r\n           -4\r\n       3.1416\r\n<\/pre><h3>Combine Techniques<a name=\"13\"><\/a><\/h3>\r\n   <p>I am now ready to combine the ideas of logical indices and regular subscripts.  Here's some data.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">Data = rand(10,5)<\/pre><pre style=\"font-style:oblique\">Data =\r\n      0.81472      0.15761      0.65574      0.70605      0.43874\r\n      0.90579      0.97059     0.035712     0.031833      0.38156\r\n      0.12699      0.95717      0.84913      0.27692      0.76552\r\n      0.91338      0.48538      0.93399     0.046171       0.7952\r\n      0.63236      0.80028      0.67874     0.097132      0.18687\r\n      0.09754      0.14189      0.75774      0.82346      0.48976\r\n       0.2785      0.42176      0.74313      0.69483      0.44559\r\n      0.54688      0.91574      0.39223       0.3171      0.64631\r\n      0.95751      0.79221      0.65548      0.95022      0.70936\r\n      0.96489      0.95949      0.17119     0.034446      0.75469\r\n<\/pre><p>Let me pull out columns 2 and 5, if the first column is at least 0.8. I'll leave the first column as well so you can trace\r\n      what's happening.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">extractD = Data(Data(:,1)&gt;=0.8,[1 2 5])<\/pre><pre style=\"font-style:oblique\">extractD =\r\n      0.81472      0.15761      0.43874\r\n      0.90579      0.97059      0.38156\r\n      0.91338      0.48538       0.7952\r\n      0.95751      0.79221      0.70936\r\n      0.96489      0.95949      0.75469\r\n<\/pre><h3>Have You Combined Indexing Techniques?<a name=\"15\"><\/a><\/h3>\r\n   <p>If you have, what were you trying to accomplish when you mixed different kinds of indexing into a single array.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_eb600d227e3d4b3180fc83a514fb3a35() {\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='eb600d227e3d4b3180fc83a514fb3a35 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' eb600d227e3d4b3180fc83a514fb3a35';\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_eb600d227e3d4b3180fc83a514fb3a35()\"><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.11<br><\/p>\r\n<\/div>\r\n<!--\r\neb600d227e3d4b3180fc83a514fb3a35 ##### SOURCE BEGIN #####\r\n%% Indexing - Mixing It Up\r\n% I've written a bunch of posts related to\r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/ indexing>, but I\r\n% still haven't showed all the flexibility allowed.  Today I'm going to add\r\n% a variant to the list.\r\n%% Types of Indexing - a Review\r\n% Let's start with indexing using subscripts. Let's start by creating a\r\n% matrix.\r\nA = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]\r\n%%\r\n% If I want to pick out the element sitting in the second row, third\r\n% column, I simply write this\r\nel23 = A(2,3)\r\n%%\r\n% and you see result 7.\r\n%\r\n% If I want another element as well, let's say 4th row, 2nd element, I can\r\n% certainly follow my last statement with a similar one.\r\nel42 = A(4,2)\r\n%%\r\n% If I want both those elements extracted, I can try combining their\r\n% respective row and column indices.\r\nels = A([2 4],[3 2])\r\n%%\r\n% What you see is that MATLAB returns the 4 intersections, not just the\r\n% first row with the first column index, and same for second.  Instead we\r\n% get each row index combined with each column index.  To get only the two\r\n% elements we originally sought, we can convert the subscripts into another\r\n% form of index, a linear index.  With linear indexing, we think of an\r\n% array as starting with the (1,1) element, and, going down each row,\r\n% stringing out the elements into a long column.  Then we use the count\r\n% into that column vector, which has length equal to |numRows * numCols|.\r\n% Use\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/sub2ind.html\r\n% |sub2ind|> to make the transformation.\r\nlinInds = sub2ind(size(A),[2 4],[3,2])\r\n%%\r\n% and then use these to index back into |A|,\r\nA(linInds)\r\n%%\r\n% getting exactly the values expected.\r\n%%\r\n% At least I hope they are the values you expected, instead of 10 and 8.\r\n% Remember, MATLAB stores array values columnwise, i.e., column followed by\r\n% column.\r\n%% Combining Styles of Indexing\r\n% Now consider another situation, where you have a matrix and you only want\r\n% certain columns extracted, depending on the value in the corresponding\r\n% row.  Perhaps, for example, you are using |NaN| as a placeholder and you\r\n% only want columns 2 and 4 in rows that do *not* start with |NaN|. \r\n%%\r\n% One function that will be useful to us here is\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/isnan.html\r\n% |isnan|>, and the output of |isnan| is a logical array (think |true| and\r\n% |false|). If I have a vector D like this,\r\nD = [ 1 NaN 3 -4 NaN pi]'\r\n%%\r\n% I can identify which entries have |NaN| values.\r\nnanD = isnan(D);\r\nwhos nanD\r\nnanD\r\n%%\r\n% I can us logical indexing to extract the non-|NaN| entries in |D|.\r\nnonNaND = D(~nanD)\r\n%% Combine Techniques\r\n% I am now ready to combine the ideas of logical indices and regular\r\n% subscripts.  Here's some data.\r\nData = rand(10,5)\r\n%%\r\n% Let me pull out columns 2 and 5, if the first column is at least 0.8.\r\n% I'll leave the first column as well so you can trace what's happening.\r\nextractD = Data(Data(:,1)>=0.8,[1 2 5])\r\n%% Have You Combined Indexing Techniques?\r\n% If you have, what were you trying to accomplish when you mixed different\r\n% kinds of indexing into a single array.  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=248#respond here>.\r\n##### SOURCE END ##### eb600d227e3d4b3180fc83a514fb3a35\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I've written a bunch of posts related to indexing, but I still haven't showed all the flexibility allowed.  Today I'm going to add a variant to the list.\r\n      \r\n   \r\n  ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2010\/10\/07\/indexing-mixing-it-up\/\">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\/249"}],"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=249"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/249\/revisions"}],"predecessor-version":[{"id":1945,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/249\/revisions\/1945"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=249"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=249"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=249"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}