Reading an Undelimited Text File Containing a Binary Matrix

3 views (last 30 days)
Hi,
I have been trying to find a smart way to read a .txt file where each row of the file has the following format: 101101101 etc. for a number of rows. I would like the corresponding row in my matrix to be [1 0 1 1 0 1 1 0 1]. I know the size of the matrix beforehand.
Is there a smart way to do this? The closest I've gotten is to read in the entire thing as cell array using textscan, then converting the character at each position into the corresponding number. Not very smart.

Answers (1)

Voss
Voss on 28 Dec 2021
Here is one way to do it:
matrix_size = 9;
fid = fopen('data.txt');
data = fread(fid);
fclose(fid);
data(data < 48 | data > 49) = [];
data = reshape(data-48,9,[]).'
data = 5×9
1 0 1 1 0 1 1 0 1 0 0 1 0 1 0 1 0 1 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0

Community Treasure Hunt

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

Start Hunting!