Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Although you can certainly do the math yourself to compute the linear index (as pointed out by <a href="https://stackoverflow.com/questions/919353/5d-array-hash-table/919404#919404">Tal</a>), it would be cleaner and easier to read using the built-in function <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sub2ind.html" rel="nofollow noreferrer">SUB2IND</a> (as pointed out by <a href="https://stackoverflow.com/questions/919353/5d-array-hash-table/920506#920506">Loren</a>). For your example, you would use it in the following way:</p> <pre><code>index = sub2ind([8 12 3 4 3], idx_r, idx_l, idx_rho, idx_alpha, idx_beta); </code></pre> <p>If all of your indices are 0-based, you would have to add 1 to each of them before passing them to SUB2IND.</p> <p><strong>EDIT:</strong></p> <p>If you would like to see how to correctly compute linear indices by yourself in MATLAB, such that they agree with the results from SUB2IND, here's the code you would use:</p> <pre><code>index = (((idx_beta*4 + idx_alpha)*3 + idx_rho)*12 + idx_l)*8 + idx_r + 1; </code></pre> <p><strong>NOTE</strong> that the indices that need to be used with this equation have to be 0-based, while the indices passed to SUB2IND have to be 1-based. To generalize this equation to an arbitrary number of dimensions <strong>N</strong>:</p> <pre><code>index = (...(idx(N)*sz(N-1) + idx(N-1))*sz(N-2) + ...)*sz(1) + idx(1) + 1; </code></pre> <p>or more succinctly:</p> <pre><code>index = 1 + sum(idx.*cumsum([1 sz(1:(N-1))])); </code></pre> <p>where <strong>idx</strong> is an array of 0-based index values for each dimension and <strong>sz</strong> is an array of the sizes of each dimension.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload