Is it possible to go through the elements of an array without resorting to length in a for loop?
조회 수: 803 (최근 30일)
이전 댓글 표시
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
Stephen23
2022년 5월 28일
편집: Stephen23
2022년 5월 28일
"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.
채택된 답변
DGM
2022년 5월 27일
편집: DGM
2022년 5월 27일
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.
댓글 수: 5
Image Analyst
2022년 5월 28일
I was wondering why you needed to convert a into a row vector, so I didn't and cot this curous result.
a = [1 2; 3 4];
v = a(:)
for k = v
fprintf('Checking k = %d.\n', k);
if k>2
fprintf('%d is greater than 2\n',k)
else
fprintf('%d is NOT greater than 2\n',k)
end
end
Why it does all the "Checking" lines first, I have no idea. And why it doesn't immediately follow that line with one of the "greater than" lines, I have no idea. Why are all the "greater" lines printed only after all the "Checking" lines have been printed? Also not sure why it's saying 3 and 4 are not greater than 2.
Steven Lord
2022년 5월 28일
"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.
추가 답변 (1개)
Jan
2022년 5월 28일
편집: Jan
2022년 5월 28일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!