While loop for the elements of an array

Illustration
Giorgos - 2023-03-13T15:05:02+00:00
Question: While loop for the elements of an array

I have an array:   a=[1 1 1 1 1 1 1 10 1 1 1 1 1 1 12 1 1 1 1 3]; I want to make a while loop that does the following enas=0; while a(i)==1 % enas=enas+1; end But I don't know how to express it in matlab. Can you help me please?

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

Here's how you'd do it:

 

a=[1 1 1 1 1 1 1 10 1 1 1 1 1 1 12 1 1 1 1 3];
enas=0;
k = 1;
while a(k)==1 % 
  enas=enas+1
  k = k + 1
end

But here's how a real MATLAB programmer would do it:

enas = find(a~=1, 1, 'first')-1

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!