I need to be able to return the indices [x1 x2 ... xd] of the elements of a matrix of dimensions LxLxL..xL. The number of dimensions d is a variable supplied to my function.
I assume by "the indices [x1 x2 ... xd]" you mean the subscripts along each dimension of the equivalent d-dimensional array.
You need to convert L and d to a dimension array, and then capture multiple argouts from ind2sub
. Here's a function that does so. You can call it like 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're storing it in a linear array and calculating subscripts, 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's efficient, and you can index in to it using either multidimensional subscripts or linear indexing. If you have a linear array, just call reshape(myarray, sz)
to convert it to the multidimensional equivalent.