Is it possible to go through the elements of an array without resorting to length in a for loop?

84 views (last 30 days)
Was just thinking whether there is something similiar to the below 'for loop of python
a=[1,2,3];
for i in a:
if i>2:
print('Greater than 2')
in MATLAB where I could go through the elements of the array itself in a for loop instead of using the 'length' as a means to acheive the same. In MATLAB I would use:
a=[1,2,3];
for i=1:length(a)
if a(i)>2:
disp('Greater than 2')
end
end
But is it possible to have something similar to Python where instead of using the 'length' I could directly use the array elements itself?
Thanks
  1 Comment
Stephen23
Stephen23 on 28 May 2022
Edited: Stephen23 on 28 May 2022
"in MATLAB where I could go through the elements of the array itself in a for loop..."
It is certainly possible to iterate over data values directly (the FOR operator does not care what kind of array you give it to iterate over), but in general with MATLAB it is simpler and easier to iterate over the array size (i.e. indices) rather than iterating over data, because invariably those indices will also be required in multiple locations for array preallocation, accessing the input data, and storing output data. Here is a recent example: https://www.mathworks.com/matlabcentral/answers/1728045-how-to-store-multiple-output-tables-in-a-cell-array
"...instead of using the 'length' as a means to acheive the same"
Avoid LENGTH because what dimension it measures depends on the size of the array, its use is a latent bug on any matrix or array. For robust code use NUMEL or SIZE of a specific dimension.

Sign in to comment.

Accepted Answer

DGM
DGM on 27 May 2022
Edited: DGM on 27 May 2022
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
3 is greater than 2 4 is greater than 2
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.
  5 Comments
Steven Lord
Steven Lord on 28 May 2022
If you look at the documentation for the for keyword:
"for index = values, statements, end executes a group of statements in a loop for a specified number of times. values has one of the following forms:
...
  • valArray — Create a column vector, index, from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes a maximum of n times, where n is the number of columns of valArray, given by numel(valArray(1,:)). The input valArray can be of any MATLAB® data type, including a character vector, cell array, or struct."
How do the sprintf and fprintf functions work with vectors as the data inputs? "fprintf(fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order"
As for why 3 and 4 are not greater than 2, that's the standard behavior of the if keyword with a non-scalar condition.

Sign in to comment.

More Answers (1)

Jan
Jan on 28 May 2022
Edited: Jan on 28 May 2022
Yes, this works:
a = [1,2,3];
for i = a
if i > 2
fprintf('%d is greater than 2\n', i)
end
end
Notes:
  • It is unusual to use "i" as loop index in Matlab, because a confusion with 1i is assumed sometimes. But the code works fine, if you avoid to use "i" as imaginary unit.
  • FOR loops work faster in the form: for k = a:b . Then the vector a:b is not created explicitly, which saves the time for the allocation.
  • The loop index is applied as columns. So if you provide a matrix, the index is a vector:
iLoop = 0;
for k = [1, 2, 3; 4, 5, 6]
iLoop = iLoop + 1;
fprintf('Iteration %d\n', iLoop);
disp(k)
fprintf('\n')
end
Iteration 1
1
4
Iteration 2
2
5
Iteration 3
3
6
Therefore DGM used:
for k = a(:).'
to convert a to a row vector.
  3 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!