{"id":97,"date":"2007-06-29T09:36:32","date_gmt":"2007-06-29T14:36:32","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2007\/06\/29\/sum-things-to-consider\/"},"modified":"2016-08-03T14:45:06","modified_gmt":"2016-08-03T19:45:06","slug":"sum-things-to-consider","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/06\/29\/sum-things-to-consider\/","title":{"rendered":"sum Things to Consider"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I was just helping someone debug a piece of code that was giving an incorrect answer.  The code returned an output with a\r\n         shape different than the coder expected.  I made sure the workspace browser was showing while we worked, and as we stepped\r\n         through the algorithm, we were able to see exactly where the problem occurred.  And it was the call to <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/sum.html\"><tt>sum<\/tt><\/a>.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">By Default, Column-wise Operations<\/a><\/li>\r\n         <li><a href=\"#2\">User Issue and Solution<\/a><\/li>\r\n         <li><a href=\"#5\">Examples<\/a><\/li>\r\n         <li><a href=\"#10\">How Can That Be?<\/a><\/li>\r\n         <li><a href=\"#11\">Ever Used Dimension to Your Advantage?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>By Default, Column-wise Operations<a name=\"1\"><\/a><\/h3>\r\n   <p>By default, MATLAB performs many operations by treating the columns as individual vectors and acting on them.  However, if\r\n      the array has only a single element per column, then MATLAB performs the operation along the first non-singleton dimension.\r\n   <\/p>\r\n   <h3>User Issue and Solution<a name=\"2\"><\/a><\/h3>\r\n   <p>So, that's the default behavior.  However, for this user's application, he always wanted the sum to be along the first dimension\r\n      (down the columns), <b>even if there was only a single entry per column<\/b>.\r\n   <\/p>\r\n   <p>To accomplish this, the altered code used the optional second input argument, <i>dimension<\/i>.  This works similarly with other functions that typically reduce the dimensionality from the input to the output, such as\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cumsum.html\"><tt>cumsum<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/prod.html\"><tt>prod<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cumprod.html\"><tt>cumprod<\/tt><\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/diff.html\"><tt>diff<\/tt><\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Here's the relevant portion of the help for <tt>sum<\/tt>. I happen to know that I only need to go up through the second instance of <tt>DIM<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">h = help(<span style=\"color: #A020F0\">'sum'<\/span>);\r\nf = strfind(h,<span style=\"color: #A020F0\">'DIM'<\/span>);\r\ndisp(h(1:f(2)+5))<\/pre><pre style=\"font-style:oblique\"> SUM Sum of elements.\r\n    S = SUM(X) is the sum of the elements of the vector X. If\r\n    X is a matrix, S is a row vector with the sum over each\r\n    column. For N-D arrays, SUM(X) operates along the first\r\n    non-singleton dimension.\r\n    If X is floating point, that is double or single, S is\r\n    accumulated natively, that is in the same class as X,\r\n    and S has the same class as X. If X is not floating point,\r\n    S is accumulated in double and S has class double.\r\n \r\n    S = SUM(X,DIM) sums along the dimension DIM. \r\n\r\n<\/pre><h3>Examples<a name=\"5\"><\/a><\/h3>\r\n   <p>Let's see this behavior in action.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">n = 4;\r\nA = cat(3, pascal(4), magic(4), invhilb(4), hadamard(4), hilb(4))<\/pre><pre style=\"font-style:oblique\">A(:,:,1) =\r\n     1     1     1     1\r\n     1     2     3     4\r\n     1     3     6    10\r\n     1     4    10    20\r\nA(:,:,2) =\r\n    16     2     3    13\r\n     5    11    10     8\r\n     9     7     6    12\r\n     4    14    15     1\r\nA(:,:,3) =\r\n          16        -120         240        -140\r\n        -120        1200       -2700        1680\r\n         240       -2700        6480       -4200\r\n        -140        1680       -4200        2800\r\nA(:,:,4) =\r\n     1     1     1     1\r\n     1    -1     1    -1\r\n     1     1    -1    -1\r\n     1    -1    -1     1\r\nA(:,:,5) =\r\n    1.0000    0.5000    0.3333    0.2500\r\n    0.5000    0.3333    0.2500    0.2000\r\n    0.3333    0.2500    0.2000    0.1667\r\n    0.2500    0.2000    0.1667    0.1429\r\n<\/pre><p>Sum <tt>A<\/tt> down the columns.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sumA = sum(A)<\/pre><pre style=\"font-style:oblique\">sumA(:,:,1) =\r\n     4    10    20    35\r\nsumA(:,:,2) =\r\n    34    34    34    34\r\nsumA(:,:,3) =\r\n    -4    60  -180   140\r\nsumA(:,:,4) =\r\n     4     0     0     0\r\nsumA(:,:,5) =\r\n    2.0833    1.2833    0.9500    0.7595\r\n<\/pre><p>Sum <tt>A<\/tt> along the rows.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sumA2 = sum(A,2)<\/pre><pre style=\"font-style:oblique\">sumA2(:,:,1) =\r\n     4\r\n    10\r\n    20\r\n    35\r\nsumA2(:,:,2) =\r\n    34\r\n    34\r\n    34\r\n    34\r\nsumA2(:,:,3) =\r\n    -4\r\n    60\r\n  -180\r\n   140\r\nsumA2(:,:,4) =\r\n     4\r\n     0\r\n     0\r\n     0\r\nsumA2(:,:,5) =\r\n    2.0833\r\n    1.2833\r\n    0.9500\r\n    0.7595\r\n<\/pre><p>Sum <tt>A<\/tt> across the third dimension.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sumA3 = sum(A,3)<\/pre><pre style=\"font-style:oblique\">sumA3 =\r\n  1.0e+003 *\r\n    0.0350   -0.1155    0.2453   -0.1248\r\n   -0.1125    1.2123   -2.6858    1.6912\r\n    0.2513   -2.6888    6.4912   -4.1788\r\n   -0.1338    1.6972   -4.1758    2.8221\r\n<\/pre><p>Try summing <tt>A<\/tt> along the 7th dimension.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sumA7 = sum(A,7)<\/pre><pre style=\"font-style:oblique\">sumA7(:,:,1) =\r\n     1     1     1     1\r\n     1     2     3     4\r\n     1     3     6    10\r\n     1     4    10    20\r\nsumA7(:,:,2) =\r\n    16     2     3    13\r\n     5    11    10     8\r\n     9     7     6    12\r\n     4    14    15     1\r\nsumA7(:,:,3) =\r\n          16        -120         240        -140\r\n        -120        1200       -2700        1680\r\n         240       -2700        6480       -4200\r\n        -140        1680       -4200        2800\r\nsumA7(:,:,4) =\r\n     1     1     1     1\r\n     1    -1     1    -1\r\n     1     1    -1    -1\r\n     1    -1    -1     1\r\nsumA7(:,:,5) =\r\n    1.0000    0.5000    0.3333    0.2500\r\n    0.5000    0.3333    0.2500    0.2000\r\n    0.3333    0.2500    0.2000    0.1667\r\n    0.2500    0.2000    0.1667    0.1429\r\n<\/pre><h3>How Can That Be?<a name=\"10\"><\/a><\/h3>\r\n   <p>Why did I get no error for summing along dimension 7 when I only have a 3 dimensional array?  The reason is that MATLAB treats\r\n      all arrays as having an infinite number of dimensions, most of them trailing singletons.  So if I sum along the 7th dimension\r\n      here, I am only summing single elements, or effectively in this case just returning the original array.\r\n   <\/p>\r\n   <h3>Ever Used Dimension to Your Advantage?<a name=\"11\"><\/a><\/h3>\r\n   <p>Have you ever used the dimension argument to your advantage?  Or tripped over the issue of having an unexpected singleton\r\n      dimension?  Any thoughts, please post them <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=97#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_66ef6f170237461cb556d449068945a0() {\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='66ef6f170237461cb556d449068945a0 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 66ef6f170237461cb556d449068945a0';\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_66ef6f170237461cb556d449068945a0()\"><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\n66ef6f170237461cb556d449068945a0 ##### SOURCE BEGIN #####\r\n%% sum Things to Consider\r\n% I was just helping someone debug a piece of code that was giving an\r\n% incorrect answer.  The code returned an output with a shape different\r\n% than the coder expected.  I made sure the workspace browser was showing\r\n% while we worked, and as we stepped through the algorithm, we were able to\r\n% see exactly where the problem occurred.  And it was the call to \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/sum.html |sum|>.\r\n%\r\n%% By Default, Column-wise Operations\r\n% By default, MATLAB performs many operations by treating the columns as\r\n% individual vectors and acting on them.  However, if the array has only a\r\n% single element per column, then MATLAB performs the operation along the\r\n% first non-singleton dimension.\r\n%% User Issue and Solution\r\n% So, that's the default behavior.  However, for this user's application,\r\n% he always wanted the sum to be along the first dimension (down the\r\n% columns), *even if there was only a single entry per column*.  \r\n%%\r\n% To accomplish this, the altered code used the optional second input\r\n% argument, _dimension_.  This works similarly with other functions that\r\n% typically reduce the dimensionality from the input to the output, such as\r\n%\r\n% * <https:\/\/www.mathworks.com\/help\/matlab\/ref\/cumsum.html |cumsum|> \r\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/prod.html |prod|> \r\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/cumprod.html |cumprod|>\r\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/diff.html |diff|>\r\n%\r\n%%\r\n% Here's the relevant portion of the help for |sum|. I happen to know that\r\n% I only need to go up through the second instance of |DIM|.\r\nh = help('sum');\r\nf = strfind(h,'DIM');\r\ndisp(h(1:f(2)+5))\r\n%% Examples\r\n% Let's see this behavior in action.\r\nn = 4;\r\nA = cat(3, pascal(4), magic(4), invhilb(4), hadamard(4), hilb(4))\r\n%%\r\n% Sum |A| down the columns.\r\nsumA = sum(A)\r\n%%\r\n% Sum |A| along the rows.\r\nsumA2 = sum(A,2)\r\n%%\r\n% Sum |A| across the third dimension.\r\nsumA3 = sum(A,3)\r\n%%\r\n% Try summing |A| along the 7th dimension.\r\nsumA7 = sum(A,7)\r\n%% How Can That Be?\r\n% Why did I get no error for summing along dimension 7 when I only have a 3\r\n% dimensional array?  The reason is that MATLAB treats all arrays as having\r\n% an infinite number of dimensions, most of them trailing singletons.  So\r\n% if I sum along the 7th dimension here, I am only summing single elements,\r\n% or effectively in this case just returning the original array.\r\n%% Ever Used Dimension to Your Advantage?\r\n% Have you ever used the dimension argument to your advantage?  Or tripped\r\n% over the issue of having an unexpected singleton dimension?  Any\r\n% thoughts, please post them <https:\/\/blogs.mathworks.com\/loren\/?p=97#respond here>.\r\n\r\n##### SOURCE END ##### 66ef6f170237461cb556d449068945a0\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I was just helping someone debug a piece of code that was giving an incorrect answer.  The code returned an output with a\r\n         shape different than the coder expected.  I... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/06\/29\/sum-things-to-consider\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,14],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/97"}],"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=97"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/97\/revisions"}],"predecessor-version":[{"id":1919,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/97\/revisions\/1919"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=97"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=97"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=97"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}