Is it possible to go through the elements of an array without resorting to length in a for loop?
Show older comments
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
"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.
Accepted Answer
More Answers (1)
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.
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!