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?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Anushka
am 7 Jul. 2015
Kommentiert: Steven Lord
am 7 Jul. 2015
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 Kommentare
Thorsten
am 7 Jul. 2015
Or
sum(double(St) == double('1'))
or
numel(findstr(St, '1'))
Steven Lord
am 7 Jul. 2015
Or, with no arithmetic (besides NNZ's counting):
nnz(str == '1')
Akzeptierte Antwort
Azzi Abdelmalek
am 7 Jul. 2015
Bearbeitet: Azzi Abdelmalek
am 7 Jul. 2015
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
0 Kommentare
Weitere Antworten (1)
Debarati Banerjee
am 7 Jul. 2015
This seems to work:
St='010101';
count=0;
a=0;
for i=1:6
a=St(1,i);
if(str2num(a)==1)
count=count+1;
end
end
Siehe auch
Kategorien
Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!