there's a question that asks to find the number of 1s in a binary string Example if the input string is '10100011' the output is 4. I wanted first to split the numbers in the string like this '1 0 1 0 0 0 1 1' then convert the string to double and get the sum But I couldn't find a way to split the number in the string
To get the number of '1'
characters in '10100011'
you can do
s = '10100011';
n = sum(s=='1');
% or equivalently
n = nnz(s=='1');
to answer your question directly, you could create an array of each digit in a char using
s = arrayfun(@str2double,s)
% s = [1, 0, 1, 0, 0, 0, 1, 1]
But in the case of a string purely composed of the characters '0'
or '1'
this is equivalent to checking if each character is =='1'
, albeit slower and less preferable to the comparison shown first.