For loop iteration issue

조회 수: 1 (최근 30일)
Bahaa Soliman
Bahaa Soliman 2021년 3월 20일
댓글: Bahaa Soliman 2021년 3월 20일
I have a binary thresholded Image that I want to loop through its matrix using a for loop.
In python, I would write the code like this:
for i in binaryImage:
...
(you get the point!)
How do I loop through the binaryImage matrix I have in MATLAB for further operations?

답변 (1개)

Steven Lord
Steven Lord 2021년 3월 20일
편집: Steven Lord 2021년 3월 20일
Loop through elements?
A = magic(4);
s = 0;
for elt = 1:numel(A)
s = s + A(elt);
end
fprintf("The sum of elements in a 4-by-4 magic sum is %d.", s)
The sum of elements in a 4-by-4 magic sum is 136.
Through columns?
cs = zeros(4, 1);
for col = 1:width(A)
cs = cs + A(:, col);
end
fprintf("The sum of the columns is")
The sum of the columns is
disp(cs)
34 34 34 34
or you can just use the array as the indices.
cs2 = zeros(4, 1);
for col = A
cs2 = cs2 + col;
end
fprintf("The sum of the columns is also")
The sum of the columns is also
disp(cs2)
34 34 34 34
Through rows?
rs = zeros(1, 4);
for row = 1:height(A)
rs = rs + A(row, :);
end
fprintf("The sum of the rows is")
The sum of the rows is
disp(rs)
34 34 34 34
Do you need to loop?
Depending on what you want to do, though, you may not need to loop.
fprintf("A has %d elements greater than 11", nnz(A > 11))
A has 5 elements greater than 11
  댓글 수: 1
Bahaa Soliman
Bahaa Soliman 2021년 3월 20일
Thank you Steven

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Image Data Workflows에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by