For loops and how to stop when a value is reached

30 views (last 30 days)
I have an array A = [0 0 0 0 1 1 1] i'm reading it using a loop i = 1:length(A) inside this forloop i have a if statement if A(i) == 1 B = 1
how can i stop it running the for loop when i get to a position where A(i) = 1
Alternatively I just want B to equal 1 when the array contains a non zero number within it somewhere and B=0 when there is all zeros.

Answers (2)

Image Analyst
Image Analyst on 25 Aug 2012
To answer the breaking out of the for loop question.....How about
if A(i) == 1
break;
end
There are many ways to get what you want, such as the any() method the others gave. You could also do others if you wanted, but the any() method is probably the best.
B1 = any(A ~= 0)
B2 = find(A, 1, 'first') > 0
B3 = sum(A ~= 0) > 0

Azzi Abdelmalek
Azzi Abdelmalek on 25 Aug 2012
Edited: Azzi Abdelmalek on 25 Aug 2012
you ca use
B=max(A);
or
B=any(A~=0)
  1 Comment
Matt Fig
Matt Fig on 25 Aug 2012
B = any(A)
B will equal zero if A has all zeros, and B will equal 1 if A does not have all zeros. The difference between what I suggest and Azzi's second suggestion above is in what happens if A has a NaN. You will have to decide what you want in this situation.
B = any([0 0 nan 0]) % Returns false.
B = any([0 0 nan 0]~=0) % Returns true.
If there is no possibility of a NaN (A is logical or whatever), then any(A) is simpler.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!