You could do something like this a = [1 2; 3 4]; for k = a(:).' % reshape a into a row vector if k>2 fprintf('%d is greater than 2\n',k) end end but I don't really think it's as readable. There are probably other options. Bear in mind that using length() will break your example if a is not a vector. Use numel() instead. Answer from DGM on mathworks.com
Discussions

Repeating a task for each row without loop
Repeating a task for each row without loop. Learn more about without loop., loop, for loop, for, vectorization, cell arrays, matlab, end More on mathworks.com
๐ŸŒ mathworks.com
1
0
March 27, 2018
arrays - How do I iterate through each element in an n-dimensional matrix in MATLAB? - Stack Overflow
I have a problem. I need to iterate through every element in an n-dimensional matrix in MATLAB. The problem is, I don't know how to do this for an arbitrary number of dimensions. I know I can say ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Efficiently populating an array without for loops
Efficiently populating an array without for loops. Learn more about for loop, matrix manipulation More on mathworks.com
๐ŸŒ mathworks.com
3
0
May 27, 2012
Iterating over a cell array: do for loops work?
Iterating over a cell array: do for loops work?. Learn more about cell array, for loop MATLAB More on mathworks.com
๐ŸŒ mathworks.com
1
0
March 28, 2024
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 470124-iterating-through-an-array-without-using-a-for-loop
Iterating through an array without using a for loop - MATLAB Answers - MATLAB Central
July 3, 2019 - I want to index through theta and assign each index a random value without using a forloop. Is there a better and faster way to preallocate theta? theta = 0:0.1:2*pi/5 theta(1:1:length(theta)) = ...
๐ŸŒ
MathWorks
mathworks.com โ€บ matlab โ€บ external language interfaces โ€บ c with matlab โ€บ call c from matlab
Iterate Through lib.pointer Object - MATLAB & Simulink
if not(libisloaded('shrlibsample')) addpath(fullfile(matlabroot,'extern','examples','shrlib')) loadlibrary('shrlibsample') end ยท Call the getListOfStrings function to create an array of character vectors. The function returns a pointer to the array. ptr = calllib('shrlibsample','getListOfStrings'); class(ptr) ... Create indexing variables to iterate through the arrays.
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 353971-iteration-without-the-implementation-of-loops
Iteration Without the Implementation of Loops - MATLAB Answers - MATLAB Central
I suppose you could use an implicit loop too, in the form of cellfun. But the above works. ... https://www.mathworks.com/matlabcentral/answers/353971-iteration-without-the-implementation-of-loops#comment_479581
Top answer
1 of 8
95

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()

2 of 8
36

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.)

Find elsewhere
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 39573-efficiently-populating-an-array-without-for-loops
Efficiently populating an array without for loops - MATLAB Answers - MATLAB Central
May 27, 2012 - I would hope this is faster than your current loop, although there are probably clever ways to use accumarray without all the looping guff I've done. Apologies if there are errors in this code. I just hacked it straight into my web browser =) ... https://www.mathworks.com/matlabcentral/answers/39573-efficiently-populating-an-array-without-for-loops#comment_81905
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 2100341-iterating-over-a-cell-array-do-for-loops-work
Iterating over a cell array: do for loops work? - MATLAB Answers - MATLAB Central
March 28, 2024 - https://www.mathworks.com/matlabcentral/answers/2100341-iterating-over-a-cell-array-do-for-loops-work#comment_3114321 ... Of course they do. It would be odd if they did not. Here are some ways to index into a cell array:
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 375648-how-to-apply-a-function-to-an-indexed-array-without-loop
How to apply a function to an indexed array without loop - MATLAB Answers - MATLAB Central
January 4, 2018 - Is there a way to do the following A = rand(100,2); c = randi(5,[100,1]); for i = 1:5 B(i, :) = mean(A(c == i, :)); end without a loop? A is my input data, c is some...
๐ŸŒ
Reddit
reddit.com โ€บ r/matlab โ€บ how to iterate through matrices
r/matlab on Reddit: How to iterate through matrices
October 27, 2020 -

I have 3 matrices(4x4) (M0T1, M1T2, M2T3) and need to assign them the following value

I have 'theta', 'alpha', 'a' and 'd' in separate 3*1 matrices, is there any way to loop through the 4x4 matrices to assign them these values as you cant make a matrix of matrices .

i.e. what in other programing languages would be 3 nested for loop with a matrix foo = [M0T1, M1T2, M2T3] and accessed by foo(i, j, k), where i would be the matrix and j & k the row & column

๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 736642-iteration-without-any-loop
Iteration without any loop. - MATLAB Answers - MATLAB Central
February 4, 2021 - I am working on B-spline, this code is to get a matrix as an output. function [M] = Iterations(N) % N is an input variable I=eye(N+1);M=zeros(N+1,N+1); % I is a diagnal matrix and M is inicial...
Top answer
1 of 9
154

MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.

A = 1:5;

for i = A
    A = B;
    disp(i);
end

If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:

n = 10;
f = n;
while n > 1
    n = n-1;
    f = f*n;
end
disp(['n! = ' num2str(f)])

Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:

A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);

itr = A.listIterator();

while itr.hasNext()

    k = itr.next();
    disp(k);

    % modify data structure while iterating
    itr.remove();
    itr.add(k);

end
2 of 9
97

Zach is correct about the direct answer to the question.

An interesting side note is that the following two loops do not execute the same:

for i=1:10000
  % do something
end
for i=[1:10000]
  % do something
end

The first loop creates a variable i that is a scalar and it iterates it like a C for loop. Note that if you modify i in the loop body, the modified value will be ignored, as Zach says. In the second case, Matlab creates a 10k-element array, then it walks all elements of the array.

What this means is that

for i=1:inf
  % do something
end

works, but

for i=[1:inf]
  % do something
end

does not (because this one would require allocating infinite memory). See Loren's blog for details.

Also note that you can iterate over cell arrays.

๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 478315-using-for-loop-for-arrays
Using for loop for arrays - MATLAB Answers - MATLAB Central
August 30, 2019 - Note that as usual in matlab, there's no need for a loop for this ... Thank you. I tried the similar approach for other values. But that doesn't seem to work the same way. ... a = [45, 56, 66, 78, 54, 67, 56, 88, 95, 93, 23, 56, 78, 45, 67, 56, 34, 67, 87, 64, 94, 57, 61, 24, 96, 98, 100, 109]; ... The variables "count2" and "count3" return output as 28, which is the array size.