<p>I am working on a function to establish the entropy of a distribution.  It uses a copula, if any are familiar with that.  I need to sum up the values in the array based on which dimensions are &quot;cared about.&quot;</p>
<p>Example:  Consider the following example...</p>
<pre>
Dimension 0 (across)
_ _ _ _ _ _ _ _ _ _ _ _ _
|_ 0 _|_ 0 _|_ 0 _|_ 2 _|  Dimension 1
|_ 1 _|_ 0 _|_ 2 _|_ 0 _|   (down)
|_ 0 _|_ 3 _|_ 0 _|_ 6 _|
|_ 0 _|_ 0 _|_ 0 _|_ 0 _|

I "care about" dimension 0 only, and "don't care" about the rest (dim 1).
Summing this array with the above specifications will
"collapse" the "stacks" of dimension 1 down to a single 4 x 1 array:

_ _ _ _ _ _ _ _ _ _ _ _ _ 
|_ 1 _|_ 3 _|_ 2 _|_ 8 _|

This can then be summed, or have any operation performed.
</pre>
<p>I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest.  I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful.</p>
<h3>Update:</h3>
<p>Just got home.  Here is some info to answer your questions:</p>
<ol>
<li>Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia.  This wasn't the case, as I found out.</li>
<li>@jeff - What doesnt make sense?  I am using this great service for (what I think is) a legit reason.  I want to get better at my hobby, which is all it is, as I am in high school.  Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation).</li>
<li>I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array.  For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation.  For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a &quot;driver&quot; function to traverse the tree as necessary, returning whatever the function is designed to do.  This is flexible, so I can accomodate a lot of different methods of accessing the array.</li>
<li>The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube).</li>
</ol>
<p>Thanks everyone for your imput.</p>

[{'answer_id': 23196, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': "<p>Actually, by colllapsing the colums you already summed them, so the dimension doesn't matter at all for your example. Did I miss something or did you?</p>\n"}, {'answer_id': 23210, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 0, 'selected': False, 'text': '<p>I think the best thing to do here would be one/both of two things:</p>\n\n<ol>\n<li>Rethink the design, if its too complex, find a less-complex way.</li>\n<li>Stop trying to visualise it.. :P Just store the dimensions in question that you need to sum, then do them one at a time. Once you have the base code, then look at improving the efficiency of your algorithm.</li>\n</ol>\n'}, {'answer_id': 23225, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 0, 'selected': False, 'text': '<p>I beg to differ, there is ALWAYS another way..</p>\n\n<p>And if you really <em>cannot</em> refactor, then you need to break the problem down into smaller parts.. Like I said, establish which dimensions you need to sum, then hit them one at a time..</p>\n\n<p>Also, stop changing the edits, they are correcting your spelling errors, they are trying to help you ;)</p>\n'}, {'answer_id': 23226, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 0, 'selected': False, 'text': "<p>When you say you don't know how many dimensions there are, how exactly are you defining the data structures?</p>\n\n<p>At some point, someone needs to create this array, and to do that, they need to know the dimensions of the array. You can force the creator to pass in this data along with the array.</p>\n\n<p>Unless the question is to define such a data structure...</p>\n"}, {'answer_id': 23275, 'author': 'nlucaroni', 'author_id': 157, 'author_profile': 'https://Stackoverflow.com/users/157', 'pm_score': 0, 'selected': False, 'text': "<p>You're doing this in c/c++... so you have an array of array of array... you don't have to visualize 20 dimensions since that isn't how the data is laid out in memory, for a 2 dimensional:</p>\n\n<pre><code>[1] --&gt; [1,2,3,4,5,6,...]\n[2] --&gt; [1,2,3,4,5,6,...]\n[3] --&gt; [1,2,3,4,5,6,...]\n[4] --&gt; [1,2,3,4,5,6,...]\n[5] --&gt; [1,2,3,4,5,6,...]\n .           .\n .           .\n .           .\n</code></pre>\n\n<p>so, why can't you iterate across the first one summing it's contents? If you are trying to find the size, then <code>sizeof(array)/sizeof(int)</code> is a risky approach. You must know the dimension to be able to process this data, and set the memory up, so you know the depth of recursion to sum. Here is some pseudo code of what it seems you should do, </p>\n\n<pre><code>sum( n_matrix, depth )\n  running_total = 0\n  if depth = 0 then\n    foreach element in the array\n      running_total += elm\n  else \n     foreach element in the array\n       running_total += sum( elm , depth-1 )\n  return running_total\n</code></pre>\n"}, {'answer_id': 23282, 'author': 'Marc Reside', 'author_id': 1429, 'author_profile': 'https://Stackoverflow.com/users/1429', 'pm_score': 2, 'selected': False, 'text': "<p>@Jeff</p>\n\n<p>I actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question.</p>\n\n<p>@Ed</p>\n\n<p>Can you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well?</p>\n\n<p>EDIT: I'm going to try and answer the question anyways. I can't give you the code off the top of my head (it would take a while to get it right without any compiler here on this PC), but I can point you in the right direction ...</p>\n\n<p>Let's use 8 dimensions (0-7) with indexes 0 to 3 as an example. You care about only 1,2 and 6. This means you have two arrays. First, <code>array_care[4][4][4]</code> for 1,2, and 6. The <code>array_care[4][4][4]</code> will hold the end result.</p>\n\n<p>Next, we want to iterate in a very specific way. We have the array <code>input[4][4][4][4][4][4][4][4]</code> to parse through, and we care about dimensions 1, 2, and 6.</p>\n\n<p>We need to define some temporary indexes:</p>\n\n<pre><code>int dim[8] = {0,0,0,0,0,0,0,0};\n</code></pre>\n\n<p>We also need to store the order in which we want to increase the indexes:</p>\n\n<pre><code>int increase_index_order[8] = {7,5,4,3,0,6,2,1};\nint i = 0;\n</code></pre>\n\n<p>This order is important for doing what you requested.</p>\n\n<p>Define a termination flag:</p>\n\n<pre><code>bool terminate=false;\n</code></pre>\n\n<p>Now we can create our loop:</p>\n\n<pre><code>while (terminate)\n{\narray_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]];\n\nwhile ((dim[increase_index_order[i]] = 3) &amp;&amp; (i &lt; 8))\n{\ndim[increase_index_order[i]]=0;\ni++;\n}\n\nif (i &lt; 8) {\ndim[increase_index_order[i]]++; i=0;\n} else {\nterminate=true;\n}\n}\n</code></pre>\n\n<p>That should work for 8 dimensions, caring about 3 dimensions. It would take a bit more time to make it dynamic, and I don't have the time. Hope this helps. I apologize, but I haven't learned the code markups yet. :(</p>\n"}, {'answer_id': 23307, 'author': 'Adam V', 'author_id': 517, 'author_profile': 'https://Stackoverflow.com/users/517', 'pm_score': 0, 'selected': False, 'text': "<pre><code>x = number_of_dimensions;\nwhile (x &gt; 1)\n{\n  switch (x)\n  {\n    case 20:\n      reduce20DimensionArray();\n      x--;\n    break;\n    case 19:\n      .....\n  }\n}\n</code></pre>\n\n<p>(Sorry, couldn't resist.)</p>\n"}, {'answer_id': 23371, 'author': 'dmo', 'author_id': 1807, 'author_profile': 'https://Stackoverflow.com/users/1807', 'pm_score': 0, 'selected': False, 'text': '<p>If I understand correctly, you want to sum all values in the cross section defined at each "bin" along 1 dimension.  I suggest making a 1D array for your destination, then looping through each element in your array adding the value to the destination with the index of the dimension of interest.</p>\n\n<p>If you are using arbitrary number of dimensions, you must have a way of addressing elements (I would be curious how you are implementing this).  Your implementation of this will affect how you set the destination index.  But an obvious way would be with if statements checked in the iteration loops.</p>\n'}, {'answer_id': 23442, 'author': 'Daniel James', 'author_id': 2434, 'author_profile': 'https://Stackoverflow.com/users/2434', 'pm_score': 2, 'selected': False, 'text': '<p>This kind of thing is much easier if you use STL containers, or maybe <a href="http://www.boost.org/libs/multi_array/doc/index.html" rel="nofollow noreferrer">Boost.MultiArray</a>. But if you must use an array:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;boost/foreach.hpp&gt;\n#include &lt;vector&gt;\n\nint sum(int x) {\n    return x;\n}\n\ntemplate &lt;class T, unsigned N&gt;\nint sum(const T (&amp;x)[N]) {\n    int r = 0;\n    for(int i = 0; i &lt; N; ++i) {\n        r += sum(x[i]);\n    }\n    return r;\n}\n\ntemplate &lt;class T, unsigned N&gt;\nstd::vector&lt;int&gt; reduce(const T (&amp;x)[N]) {\n    std::vector&lt;int&gt; result;\n    for(int i = 0; i &lt; N; ++i) {\n        result.push_back(sum(x[i]));\n    }\n    return result;\n}\n\nint main() {\n    int x[][2][2] = {\n        { { 1, 2 }, { 3, 4 } },\n        { { 5, 6 }, { 7, 8 } }\n    };\n\n    BOOST_FOREACH(int v, reduce(x)) {\n        std::cout&lt;&lt;v&lt;&lt;"\\n";\n    }\n}\n</code></pre>\n'}, {'answer_id': 25002, 'author': 'Brendan', 'author_id': 199, 'author_profile': 'https://Stackoverflow.com/users/199', 'pm_score': 3, 'selected': True, 'text': "<p>This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid.</p>\n\n<p>I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python,</p>\n\n<pre><code>\ndef iter_arr(array):\n  sum = 0\n  for i in array:\n    if type(i) == type(list()):\n      sum = sum + iter_arr(i)\n    else:\n      sum = sum + i\n  return sum \n</code></pre>\n\n<ol>\n<li>Iterate over each element in array</li>\n<li>If element is another array, call the function again</li>\n<li>If element is not array, add it to the sum</li>\n<li>Return sum</li>\n</ol>\n\n<p>You would then apply this to each element in the 'cared about' dimension.</p>\n\n<p>This is easier in python due to duck-typing though ...</p>\n"}]
['https://Stackoverflow.com/questions/23190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/522/']