MATLAB: How to get all the outputs of the ind2sub function

matrix manipulationvariable-dimensions

Say I have a variable dimension matrix A (it could have 2,3 ..n dimensions) so I could access it by A(x1,x2,…,xn). When I use a linear index 'lin_ind' how can get the matrix coordinates for that point ?
I could use
ind2sub(size(A),lin_ind)
but the problem is how to get 'all' the outputs for a variable dimension?

Best Answer

You can preallocate a cell array to the same size as the siz input, and use this to collect all of the outputs. This will expand to whatever size siz has:
>> idx = [3 4;5 6];
>> siz = [2,2,2];
>> out = cell(size(siz));
>> [out{:}] = ind2sub(siz,idx)
out =
[2x2 double] [2x2 double] [2x2 double]