Receive multiple subscripts from linear index of matrix A, where ndim(A) is uknown.

1 view (last 30 days)
Suppose that I have a matrix A, where ndims(A) is unknown (The user defines the number of dimensions). I want to loop through the elements of A while knowing the multidimensional subscripts corresponding to each iteration. For example, if size(A)=[2,2], for iteration 1, index is [1,1], for iteration 2, index is [2,1], for iteration 3, index is [1,2] etc. I tried the following:
for i = prod(size(A))
index = ind2sub(size(A), i)
end
This doesn't work because ind2sub gives me back the linear index of the matrix. Remember, I don't know the number of dimensions of the matrix, so I can't just type [I,J]=ind2sub(...). I know that I can do that with a few more loops and a few divisions but I prefer to use Matlab functions to save operational power. Is there a function that can do that?

Accepted Answer

Sean de Wolski
Sean de Wolski on 29 Jul 2015
Steven's answer asks the why which is a good question. This is especially true since you're iterating over all of the elements in the matrix anyway so you should in theory be able to just ind2sub(size(x),1:numel(x)).
Here's how you deal with the unknown number of outputs:
A = rand(4,5,6);
nd = ndims(A);
for ii = numel(A)
[C{1:nd}] = ind2sub(size(A), ii);
end
  1 Comment
George Rossides
George Rossides on 29 Jul 2015
Thank you for the answers. I am using all of the dimensions apart from the last one on other matrices inside the loop, so I need to know their exact value at every point.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 29 Jul 2015
You could just use linear indexing. Remember that MATLAB is column-major.
A = [1 2; 3 4];
for k = 1:numel(A)
fprintf('Element %d of A is %d.\n', k, A(k));
end
Alternately look at the "Assigning to a Comma-Separated List" example or the final entry in the "How to Use the Comma-Separated Lists" section on the documentation page that discusses comma-separated lists. You can adapt those examples to call IND2SUB with the appropriate number of outputs.

Categories

Find more on Mathematics in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!