{"id":100,"date":"2007-07-26T08:54:47","date_gmt":"2007-07-26T13:54:47","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2007\/07\/26\/assignment-with-repeated-indices\/"},"modified":"2007-07-27T06:54:40","modified_gmt":"2007-07-27T11:54:40","slug":"assignment-with-repeated-indices","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/07\/26\/assignment-with-repeated-indices\/","title":{"rendered":"Assignment with Repeated Indices"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I have had customers ask me occasionally about what happens during an indexed assignment when indices are repeated. The answer\r\n         is that it depends on how you do the assignment.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Repeated Indices with a Single Assignment<\/a><\/li>\r\n         <li><a href=\"#6\">Repeated Indices Using a for Loop for the Assignment<\/a><\/li>\r\n         <li><a href=\"#8\">Using accumarray to Accumulate Results with Repeated Indices<\/a><\/li>\r\n         <li><a href=\"#10\">Repeated Index Usage<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Repeated Indices with a Single Assignment<a name=\"1\"><\/a><\/h3>\r\n   <p>I initialize an output matrix to zeros and create two vectors, one with locations (indices) and one for the corresponding\r\n      data.  Now let's look at the results of an indexed assignment.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A = zeros(3);\r\nloc = [1 3 7 9 1];\r\ndata = 1:5;\r\nA(loc) = A(loc) + data<\/pre><pre style=\"font-style:oblique\">A =\r\n     5     0     3\r\n     0     0     0\r\n     2     0     4\r\n<\/pre><p>You see in this case that even though index 1 was repeated, its output value is only 5, and not 6. Let me reset <tt>A<\/tt> so I can show you what's going on.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A = zeros(3);<\/pre><p>Here's what \"essentially\" happens during an assignment in MATLAB.  On the right-hand side, <tt>A(loc)<\/tt> is created.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(loc)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     0     0     0     0     0\r\n<\/pre><p>This means that there are 2 copies of <tt>A(1)<\/tt> currently and an element of <tt>data<\/tt> will be added to each of these.  The important thing to realize is that now the values for the right-hand side have been\r\n      calculated and set.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(loc) + data<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1     2     3     4     5\r\n<\/pre><p>Following this, the 5-element right-hand side is assigned into <tt>A(loc)<\/tt> on the left-hand side. Values are currently placed into the output vector by marching down the left-hand side locations,\r\n      replacing one element at a time.  So the first element gets replaced not once, but twice, with the final one being the value\r\n      that you see.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A(loc) = A(loc) + data<\/pre><pre style=\"font-style:oblique\">A =\r\n     5     0     3\r\n     0     0     0\r\n     2     0     4\r\n<\/pre><h3>Repeated Indices Using a for Loop for the Assignment<a name=\"6\"><\/a><\/h3>\r\n   <p>Here's another way to do the assignment, but in this case, the<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">B = zeros(3);\r\n<span style=\"color: #0000FF\">for<\/span> n = 1:length(loc)\r\n  B(loc(n)) = B(loc(n)) + data(n);\r\n<span style=\"color: #0000FF\">end<\/span>\r\nB<\/pre><pre style=\"font-style:oblique\">B =\r\n     6     0     3\r\n     0     0     0\r\n     2     0     4\r\n<\/pre><p>Notice that the output here for <tt>B<\/tt> does not match that from the vectorized assignment above.   This is because the values for the right-hand side get updated\r\n      one at a time, and can therefore accumulate as additions made to a particular index.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">isequal(A,B)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     0\r\n<\/pre><h3>Using accumarray to Accumulate Results with Repeated Indices<a name=\"8\"><\/a><\/h3>\r\n   <p>What if you want the accumulation effect, but you'd prefer to use vectorized code?  That's what the function <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/accumarray.html\"><tt>accumarray<\/tt><\/a> is for.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">C = accumarray(loc',data,[9 1]);\r\nC = reshape(C,[3 3])<\/pre><pre style=\"font-style:oblique\">C =\r\n     6     0     3\r\n     0     0     0\r\n     2     0     4\r\n<\/pre><p>We see the same results here as those from the <tt>for<\/tt> loop example.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">isequal(B,C)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Repeated Index Usage<a name=\"10\"><\/a><\/h3>\r\n   <p>Did you know this about MATLAB already?  I'm curious to hear your experiences in this area.  Post them <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=100#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_2b914e509f584fb8a6d31b990a9ebfe6() {\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='2b914e509f584fb8a6d31b990a9ebfe6 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 2b914e509f584fb8a6d31b990a9ebfe6';\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 2007 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_2b914e509f584fb8a6d31b990a9ebfe6()\"><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.4<br><\/p>\r\n<\/div>\r\n<!--\r\n2b914e509f584fb8a6d31b990a9ebfe6 ##### SOURCE BEGIN #####\r\n%% Assignment with Repeated Indices\r\n% I have had customers ask me occasionally about what happens during an\r\n% indexed assignment when indices are repeated. The answer is that it\r\n% depends on how you do the assignment.\r\n%% Repeated Indices with a Single Assignment\r\n% I initialize an output matrix to zeros and create two vectors, one with\r\n% locations (indices) and one for the corresponding data.  Now let's look\r\n% at the results of an indexed assignment.\r\nA = zeros(3);\r\nloc = [1 3 7 9 1]; \r\ndata = 1:5;\r\nA(loc) = A(loc) + data\r\n%% \r\n% You see in this case that even though index 1 was repeated, its output\r\n% value is only 5, and not 6. \r\n% Let me reset |A| so I can show you what's going on.\r\nA = zeros(3);\r\n%%\r\n% Here's what \"essentially\" happens during an\r\n% assignment in MATLAB.  On the right-hand side, |A(loc)| is created.\r\nA(loc)\r\n%%\r\n% This means that there are 2 copies of |A(1)| currently and an element of\r\n% |data| will be added to each of these.  The important thing to realize\r\n% is that now the values for the right-hand side have been calculated and\r\n% set. \r\nA(loc) + data\r\n%%\r\n% Following this, the 5-element\r\n% right-hand side is assigned into |A(loc)| on the left-hand side. Values\r\n% are currently placed into the output vector by marching down the\r\n% left-hand side locations, replacing one element at a time.  So the first\r\n% element gets replaced not once, but twice, with the final one being the\r\n% value that you see.\r\nA(loc) = A(loc) + data\r\n%% Repeated Indices Using a for Loop for the Assignment\r\n% Here's another way to do the assignment, but in this case, the \r\nB = zeros(3);\r\nfor n = 1:length(loc)\r\n  B(loc(n)) = B(loc(n)) + data(n);\r\nend\r\nB\r\n%%\r\n% Notice that the output here for |B| does not match that from the\r\n% vectorized assignment above.   This is because the values for the\r\n% right-hand side get updated one at a time, and can therefore accumulate\r\n% as additions made to a particular index.\r\nisequal(A,B)\r\n%% Using accumarray to Accumulate Results with Repeated Indices\r\n% What if you want the accumulation effect, but you'd prefer to use\r\n% vectorized code?  That's what the function\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/accumarray.html |accumarray|>\r\n% is for.\r\nC = accumarray(loc',data,[9 1]);\r\nC = reshape(C,[3 3])\r\n%%\r\n% We see the same results here as those from the |for| loop example.\r\nisequal(B,C)\r\n%% Repeated Index Usage\r\n% Did you know this about MATLAB already?  I'm curious to hear your\r\n% experiences in this area.  Post them\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=100#respond here>.\r\n\r\n##### SOURCE END ##### 2b914e509f584fb8a6d31b990a9ebfe6\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I have had customers ask me occasionally about what happens during an indexed assignment when indices are repeated. The answer\r\n         is that it depends on how you do the... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/07\/26\/assignment-with-repeated-indices\/\">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,15],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/100"}],"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=100"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/100\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}