How do I iterate through each element in an n-dimensional matrix in MATLAB?
You can use linear indexing to access each element.
for idx = 1:numel(array)
element = array(idx)
....
end
This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()
The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
A(2,3)
ans =
7
A(8)
ans =
7
We can see the order the elements are stored in memory by unrolling the array into a vector.
A(:)
ans =
8
3
4
1
5
9
6
7
2
As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.
find(A>6)
ans =
1
6
8
The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:
B = zeros(size(A));
for i = 1:numel(A)
B(i) = A(i).^2;
end
B
B =
64 1 36
9 25 49
16 81 4
There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.
The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)