2

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. The matrix does not exist, instead I have a linear array of length L^d. For a given index i in the array, I would like to know the equivalent indices in the matrix. I can already do this using a simple for loop, but I am curious to know if I could use ind2sub somehow. The problem I have is that if I do

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

x is reassigned a single number and not an array of all subscripts. Is there a way of doing this?

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
Ivan
  • 409
  • 4
  • 17

1 Answers1

7

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.

Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
  • Thanks! This is a part of a simulation that involves multiple changes of dimensionality. – Ivan Jan 18 '12 at 22:53
  • You might just use `reshape()` then; it's cheap because it just twiddles the dimension metadata in the mxarray header; the underlying data is left as it is in memory. Effectively, Matlab's array support already does this stuff and reimplementing it in user code is probably going to make your code slower. – Andrew Janke Jan 18 '12 at 22:58