How to convert a long txt sequence of single digit numbers (e.g. '100101011101010111...') to number array?

9 views (last 30 days)
Have have sequences of 1's and 0's in a string. Each sequence is on the order of 100 million numbers. I want to convert this char into a numerical array of the same length, so that each individual char character is a single digit number in the array (a 1 or a 0). E.g. for a length 10 char variable:
s = '1000011110'
n = [1 0 0 0 0 1 1 1 1 0] (this is what I want)
Is there any way to do this without extremely long for loops?

Accepted Answer

dpb
dpb on 7 Sep 2022
Edited: dpb on 8 Sep 2022
s = '1000011110';
n = sscanf(s,'%1d')
n = 10×1
1 0 0 0 0 1 1 1 1 0
Probably fastest. Or you can compare
s = '1000011110';
n =str2num(s.')
n = 10×1
1 0 0 0 0 1 1 1 1 0
If the string data are in a file rather than being generated internally, then use the first technique and read in as numeric to begin with...
fid=fopen('yourfile.txt');
n=fscanf(fid,'%1d');
fid=fclose(fid);
ADDENDUM
Try the following to avoid the i/o library and spoof a typecast...
s = '1000011110';
n=double(s.'-'0')
ADDENDUM SECOND:
Which above can be written as
n=double(s.')-'0';
which then MATLAB syntax will do the same thing without even the explicit cast to double()...
n=s.'-'0';
or the transpose to column that the string solutions need...
n=s-'0';
  10 Comments
dpb
dpb on 13 Sep 2022
s = char(n.' + '0');
Indeed! :)
If you want the single string instead, drop the .' transpose and leave as row vector instead...

Sign in to comment.

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!