{"id":195,"date":"2008-02-08T14:50:41","date_gmt":"2008-02-08T19:50:41","guid":{"rendered":"https:\/\/blogs.mathworks.com\/steve\/2008\/02\/08\/linear-indexing\/"},"modified":"2019-10-24T13:55:13","modified_gmt":"2019-10-24T17:55:13","slug":"linear-indexing","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/steve\/2008\/02\/08\/linear-indexing\/","title":{"rendered":"Linear indexing"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <p>Last week I posted an introduction to <a href=\"https:\/\/blogs.mathworks.com\/steve\/2008\/01\/28\/logical-indexing\/\">logical indexing<\/a>.  This week I want to continue with a brief discussion of <i>linear indexing<\/i> and its connection to image processing in MATLAB.\r\n   <\/p>\r\n   <p>Lets start with a small matrix.  Breaking with tradition, I'll use a Hilbert matrix instead of a magic square:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A = hilb(5)<\/pre><pre style=\"font-style:oblique\">\r\nA =\r\n\r\n    1.0000    0.5000    0.3333    0.2500    0.2000\r\n    0.5000    0.3333    0.2500    0.2000    0.1667\r\n    0.3333    0.2500    0.2000    0.1667    0.1429\r\n    0.2500    0.2000    0.1667    0.1429    0.1250\r\n    0.2000    0.1667    0.1429    0.1250    0.1111\r\n\r\n<\/pre><p>POP QUIZ: What does the MATLAB expression <tt>A(17)<\/tt> mean?\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(17)<\/pre><pre style=\"font-style:oblique\">\r\nans =\r\n\r\n    0.2000\r\n\r\n<\/pre><p>MATLAB interprets a single subscript as an index into a vector containing all the values of <tt>A<\/tt> in column order.  So <tt>A(17)<\/tt> is the same as <tt>A(2, 4)<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(2, 4)<\/pre><pre style=\"font-style:oblique\">\r\nans =\r\n\r\n    0.2000\r\n\r\n<\/pre><p>This is called <i>linear indexing<\/i>.\r\n   <\/p>\r\n   <p>So what's the connection to image processing?  Suppose <tt>A<\/tt> is our image, and some previous computation has told us that we are interested in the pixel values at these row and column\r\n      coordinates:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">row = [2 1 5];\r\ncol = [1 3 4];<\/pre><p>Can we extract the desired pixel values in a single expression? Let's try:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(row, col)<\/pre><pre style=\"font-style:oblique\">\r\nans =\r\n\r\n    0.5000    0.2500    0.2000\r\n    1.0000    0.3333    0.2500\r\n    0.2000    0.1429    0.1250\r\n\r\n<\/pre><p>Well, we got nine values out, not three, so that certainly isn't what we are looking for.  MATLAB computes <tt>A(row, col)<\/tt> as the submatrix of <tt>A<\/tt> formed by the intersections of the specified rows and columns.\r\n   <\/p>\r\n   <p>Instead of indexing into <tt>A<\/tt> using row and column subscripts, we need to index using a single subscript.\r\n   <\/p>\r\n   <p>Here's how to convert from row-column subscripts into linear indices:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">M = size(A, 1);\r\nidx = M * (col - 1) + row<\/pre><pre style=\"font-style:oblique\">\r\nidx =\r\n\r\n     2    11    20\r\n\r\n<\/pre><p>The expression <tt>A(idx)<\/tt> pulls out just the three values we want:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(idx)<\/pre><pre style=\"font-style:oblique\">\r\nans =\r\n\r\n    0.5000    0.3333    0.1250\r\n\r\n<\/pre><p>Or we can assign to just those elements:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(idx) = Inf<\/pre><pre style=\"font-style:oblique\">\r\nA =\r\n\r\n    1.0000    0.5000       Inf    0.2500    0.2000\r\n       Inf    0.3333    0.2500    0.2000    0.1667\r\n    0.3333    0.2500    0.2000    0.1667    0.1429\r\n    0.2500    0.2000    0.1667    0.1429    0.1250\r\n    0.2000    0.1667    0.1429       Inf    0.1111\r\n\r\n<\/pre><p>The functions <tt>sub2ind<\/tt> (\"subscript\" to \"index\") and <tt>ind2sub<\/tt> convert back and forth between row-column subscripts and linear indices.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">idx = sub2ind(size(A), row, col)<\/pre><pre style=\"font-style:oblique\">\r\nidx =\r\n\r\n     2    11    20\r\n\r\n<\/pre><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[r, c] = ind2sub(size(A), idx)<\/pre><pre style=\"font-style:oblique\">\r\nr =\r\n\r\n     2     1     5\r\n\r\n\r\nc =\r\n\r\n     1     3     4\r\n\r\n<\/pre><p>For a couple of detailed image processing examples illustrating linear indexing, see these previous posts:<\/p>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"https:\/\/blogs.mathworks.com\/steve\/2007\/08\/21\/gray-scale-pixel-values-in-labeled-regions\/\">Gray-scale pixel values in labeled regions<\/a><\/li>\r\n         <li><a href=\"https:\/\/blogs.mathworks.com\/steve\/2007\/08\/31\/intensity-weighted-centroids\/\">Intensity-weighted centroids<\/a><\/li>\r\n      <\/ul>\r\n   <\/div><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_caf2f0a6086a4df8bddca0d0413b5d12() {\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='caf2f0a6086a4df8bddca0d0413b5d12 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' caf2f0a6086a4df8bddca0d0413b5d12';\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 = 'Steve Eddins';\r\n        copyright = 'Copyright 2008 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_caf2f0a6086a4df8bddca0d0413b5d12()\"><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.5<br><\/p>\r\n<\/div>\r\n<!--\r\ncaf2f0a6086a4df8bddca0d0413b5d12 ##### SOURCE BEGIN #####\r\n%% \r\n% Last week I posted an introduction to \r\n% <https:\/\/blogs.mathworks.com\/steve\/2008\/01\/28\/logical-indexing\/ \r\n% logical indexing>.  This week I want to continue with a brief \r\n% discussion of _linear indexing_ and its connection to image \r\n% processing in MATLAB.\r\n% \r\n% Lets start with a small matrix.  Breaking with tradition, I'll\r\n% use a Hilbert matrix instead of a magic square:\r\n\r\nA = hilb(5)\r\n\r\n%%\r\n% POP QUIZ: What does the MATLAB expression |A(17)| mean?\r\n\r\nA(17)\r\n\r\n%%\r\n% MATLAB interprets a single subscript as an index into a\r\n% vector containing all the values of |A| in column order.  So\r\n% |A(17)| is the same as |A(2, 4)|.\r\n\r\nA(2, 4)\r\n\r\n%%\r\n% This is called _linear indexing_.\r\n%\r\n% So what's the connection to image processing?  Suppose |A| is our\r\n% image, and some previous computation has told us that we are\r\n% interested in the pixel values at these row and column\r\n% coordinates:\r\n\r\nrow = [2 1 5];\r\ncol = [1 3 4];\r\n\r\n%%\r\n% Can we extract the desired pixel values in a single expression?\r\n% Let's try:\r\n\r\nA(row, col)\r\n\r\n%%\r\n% Well, we got nine values out, not three, so that certainly\r\n% isn't what we are looking for.  MATLAB computes |A(row, col)| as\r\n% the submatrix of |A| formed by the intersections of the specified\r\n% rows and columns.\r\n%\r\n% Instead of indexing into |A| using row and column subscripts, we\r\n% need to index using a single subscript.\r\n%\r\n% Here's how to convert from row-column subscripts into linear\r\n% indices:\r\n\r\nM = size(A, 1);\r\nidx = M * (col - 1) + row\r\n\r\n%%\r\n% The expression |A(idx)| pulls out just the three values we want:\r\n\r\nA(idx)\r\n\r\n%%\r\n% Or we can assign to just those elements:\r\n\r\nA(idx) = Inf\r\n\r\n%%\r\n% The functions |sub2ind| (\"subscript\" to \"index\") and |ind2sub|\r\n% convert back and forth between row-column subscripts and linear\r\n% indices.\r\n\r\nidx = sub2ind(size(A), row, col)\r\n\r\n%%\r\n\r\n[r, c] = ind2sub(size(A), idx)\r\n\r\n%%\r\n% For a couple of detailed image processing examples illustrating\r\n% linear indexing, see these previous posts:\r\n%\r\n% * <https:\/\/blogs.mathworks.com\/steve\/2007\/08\/21\/gray-scale-pixel-values-in-labeled-regions\/ \r\n% Gray-scale pixel values in labeled regions>\r\n% * <https:\/\/blogs.mathworks.com\/steve\/2007\/08\/31\/intensity-weighted-centroids\/ \r\n% Intensity-weighted centroids>\r\n\r\n##### SOURCE END ##### caf2f0a6086a4df8bddca0d0413b5d12\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   Last week I posted an introduction to logical indexing.  This week I want to continue with a brief discussion of linear indexing and its connection to image processing in MATLAB.\r\n   \r\n   Lets... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/steve\/2008\/02\/08\/linear-indexing\/\">read more >><\/a><\/p>","protected":false},"author":42,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[17],"tags":[462,470,190,468],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/195"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/users\/42"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/comments?post=195"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/195\/revisions"}],"predecessor-version":[{"id":3588,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/195\/revisions\/3588"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/media?parent=195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/categories?post=195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/tags?post=195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}