I have a string S='010101' I need to take each element from the string and check whether it 1,if it is one then the count is incremented by one in matlab?

I have a string S='010101' I need to take each element from the string and check whether it 1,if it is one then the count is incremented by one in matlab?
I have used the following code,but the value of count is not changing.
St='010101';
count=0;
a=0;
for i=1:6
a=St(i);
if(a==1)
count=count+1;
end
end

3 Comments

Don't use a loop for this, when vectorized code is much neater and faster:
str = '010101';
cumsum(str-'0')
nnz(str-'0')

Sign in to comment.

 Accepted Answer

S='010101'
out=nnz(S-'0')
To correct your for loop
St='010101';
count=0;
a=0;
for i=1:6
a=St(i);
if(a=='1')
count=count+1;
end
end

More Answers (1)

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!