For loops and how to stop when a value is reached

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)

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
you ca use
B=max(A);
or
B=any(A~=0)

1 Comment

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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 25 Aug 2012

Community Treasure Hunt

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

Start Hunting!