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

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?

 Akzeptierte Antwort

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 Kommentar

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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

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.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by