Note that there are some explanatory texts on larger screens.

plurals
  1. POIndexing of unknown dimensional matrix
    text
    copied!<p>I have a non-fixed dimensional matrix M, from which I want to access a single element. The element's indices are contained in a vector J.</p> <p>So for example:</p> <pre><code>M = rand(6,4,8,2); J = [5 2 7 1]; output = M(5,2,7,1) </code></pre> <p>This time M has 4 dimensions, but this is not known in advance. This is dependent on the setup of the algorithm I'm writing. It could likewise be that</p> <pre><code>M = rand(6,4); J = [3 1]; output = M(3,1) </code></pre> <p>so I can't simply use</p> <pre><code>output=M(J(1),J(2)) </code></pre> <p>I was thinking of using <a href="http://www.mathworks.nl/help/techdoc/ref/sub2ind.html" rel="nofollow">sub2ind</a>, but this also needs its variables comma separated..</p> <p>@gnovice</p> <p>this works, but I intend to use this kind of element extraction from the matrix <code>M</code> quite a lot. So if I have to create a temporary variable <code>cellJ</code> every time I access <code>M</code>, wouldn't this tremendously slow down the computation??</p> <p>I could also write a separate function</p> <pre><code>function x= getM(M,J) x=M(J(1),J(2)); % M doesn't change in this function, so no mem copy needed = passed by reference end </code></pre> <p>and adapt this for different configurations of the algorithm. This is of course a speed vs flexibility consideration which I hadn't included in my question..</p> <p>BUT: this is only available for getting the element, for setting there is no other way than actually using the indices (and preferably the linear index). I still think sub2ind is an option. The final result I had intended was something like:</p> <pre><code>function idx = getLinearIdx(J, size_M) idx = ... end </code></pre> <hr> <h2>RESULTS:</h2> <pre><code>function lin_idx = Lidx_ml( J, M )%#eml %LIDX_ML converts an array of indices J for a multidimensional array M to %linear indices, directly useable on M % % INPUT % J NxP matrix containing P sets of N indices % M A example matrix, with same size as on which the indices in J % will be applicable. % % OUTPUT % lin_idx Px1 array of linear indices % % method 1 %lin_idx = zeros(size(J,2),1); %for ii = 1:size(J,2) % cellJ = num2cell(J(:,ii)); % lin_idx(ii) = sub2ind(size(M),cellJ{:}); %end % method 2 sizeM = size(M); J(2:end,:) = J(2:end,:)-1; lin_idx = cumprod([1 sizeM(1:end-1)])*J; end </code></pre> <p>method 2 is 20 (small number of index sets (<code>=P</code>) to convert) to 80 (large number of index sets (<code>=P</code>)) times faster than method 1. easy choice</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