Problem 568. Number of 1s in a binary string

Thats the question:
Find the number of 1s in the given binary string. Example. If the input string is '1100101', the output is 4. If the input string is '0000', the output is 0
I wrote this code, but I don't understand, what is wrong with it.
function y = one(x)
y = length(find(x))
end

 채택된 답변

Les Beckham
Les Beckham 2023년 9월 8일
The find() function returns the index of all non-zero elements in the input. ASCII characters (like '0' and '1') are all non-zero (numerically) so your function will just return the length of the input string.
Example:
find('1011010')
ans = 1×7
1 2 3 4 5 6 7
length(find('1011010'))
ans = 7
There are a lot of ways to solve this problem. Look at this documentation page for one way: find characters

댓글 수: 3

Also, if you are just getting started with Matlab, I would highly recommend that you take a couple of hours to go through the free online tutorial: Matlab Onramp
Mayla
Mayla 2023년 9월 8일
I have already done Onramp. Maybe I should repeat it again :) Do you have any tipps for other free online tutorials?
Mathworks has several other tutorials in addition to the Onramp.
Check this page that lists some more: Self-Paced Online Courses

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Harald
Harald 2023년 9월 8일

3 개 추천

Hi,
find is intended for numerical non-0 elements rather than non-'0'. Instead, I would use == to compare to '0', and I would also use sum or nnz rather than length.
Best wishes,
Harald

댓글 수: 6

+1 for using just logical indexing with sum/nnz over length
@Dyuman Joshi my vote registered but yours did not for some reason.
Mayla
Mayla 2023년 9월 8일
Thanks for your answers! I found a solution, but I tried
x==1
y=sum(ans)
and it didn't work. Why is that so? And why can't I only use sum(x)?
Hi,
you need to compare to '1' instead of 1.
Also, avoid using ans. Assign to a variable instead:
isOne = x=='1';
y=sum(isOne)
% or, in one line:
y=sum(x == '1')
Best wishes,
Harald
"and it didn't work."
Because you are comparing with a numerical value
x='1011010';
x==1
ans = 1×7 logical array
0 0 0 0 0 0 0
What you want to do is compare with a character
x=='1'
ans = 1×7 logical array
1 0 1 1 0 1 0
"And why can't I only use sum(x)?"
Because that will give the sum of the values of x, which is not what the questions asks for.
What you want is, the total number of values i.e. sum where x isequal to '1'. So that's what is done.
@Image Analyst please check again

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2023년 9월 8일

댓글:

2023년 9월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by