Inverse indices of a variable dimensional matrix

I need to return the indices [x1 x2 ... xd] of the elements of the matrix of dimensions LxLxL..xL. The number of dimensions d is a variable provided by my function. The matrix does not exist, instead I have a linear array of length L ^ d. For a given index, I'm in an array, I would like to know the equivalent indexes in the matrix. I can already do this using a simple loop, but I'm curious to know if I can somehow use ind2sub. The problem is that if I do

x=zeros(1,d) x=ind2sub(L,i) 

x is reassigned to a single number, not an array of all indices. Is there any way to do this?

+2
source share
1 answer

I assume that "indices [x1 x2 ... xd]" mean indices along each dimension of an equivalent d-dimensional array.

You need to convert L and d to an array of dimensions, and then grab a few arguments from ind2sub . Here is the function that does this. You can call it as x = myind2sub(L, d, i) .

 function out = myind2sub(L, d, ix) sz = repmat(L, [1 d]); %// dimension array for a d-dimension array L long on each side c = cell([1 d]); %// dynamically sized varargout [c{:}] = ind2sub(sz, ix); out = [c{:}]; 

But you should also ask why you store it in a linear array and compute indexes, instead of just storing it in a multidimensional array in the first place. In Matlab, a multidimensional array is stored in a contiguous block of memory, so it is efficient, and you can index it using either multidimensional indexes or linear indexing. If you have a linear array, just call reshape(myarray, sz) to convert it to the multidimensional equivalent.

+6
source

Source: https://habr.com/ru/post/1502427/


All Articles