Receive multiple subscripts from linear index of matrix A, where ndim(A) is uknown.
Show older comments
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
More Answers (1)
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 Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!