Reading an Undelimited Text File Containing a Binary Matrix

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.

답변 (1개)

Voss
Voss 2021년 12월 28일
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

카테고리

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

질문:

2012년 1월 21일

답변:

2021년 12월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by