Is it possible to go through the elements of an array without resorting to length in a for loop?
11 views (last 30 days)
Was just thinking whether there is something similiar to the below 'for loop of python
for i in a:
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:
disp('Greater than 2')
But is it possible to have something similar to Python where instead of using the 'length' I could directly use the array elements itself?
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
fprintf('%d is greater than 2\n',k)
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.
More Answers (1)
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)
- 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);
Therefore DGM used:
for k = a(:).'
to convert a to a row vector.