How to read text file and save the result to .mat file

조회 수: 1 (최근 30일)
Mr. Unkown
Mr. Unkown 2014년 3월 14일
편집: dpb 2014년 3월 14일
Hi;
I have multiple text files with this format:
21
yes 1 1 1 1 0 0 1 0
yes 0 0 1 1 0 1 0 1
yes 0 1 1 0 1 0 1 1
yes 0 1 1 1 1 1 0 1
- the number of rows are different from file to file.
- I don't know the number of binary in each row(But i believe all rows have the same number)
**I need to save only the binary
I have tried this code
for i=1:1
for j=1:8
fid = fopen(strcat('C:\Experiment\Test',num2str(i),'_',num2str(j),'.txt'), 'r');
firstcell = textscan(fid, '%d', 1);
restcell = textscan(fid, '%*s%s', 'CollectOutput', 1);
fclose(fid);
firstCell = firstcell{1};
rest = restcell{1};
filename=strcat('Result', num2str(i),'_',num2str(j),'.mat');
save(filename,'rest');%,'delimiter',' ' );
end
end
The problem here is:
it saves the entire binary numbers into single column.
I need to have the file output looks like this:
1 1 1 1 0 0 1 0
0 0 1 1 0 1 0 1
0 1 1 0 1 0 1 1
*/ many thanks to Walter Roberson , for his inspiration for the above code
  댓글 수: 1
dpb
dpb 2014년 3월 14일
편집: dpb 2014년 3월 14일
Maybe there's a more clever way but nothing I can get to work at the moment...
textscan(l, ['%*s' repmat('%d',1,8)]', 'CollectOutput', 1)
You need to read a line ( fgetl is a help here) and count the number of digits if you don't know a priori to give textscan some help in the parsing.
In passing, another advantage in Fortran FORMAT, one could use recursion to skip the one string then repeat the %d w/o the explicit number of fields by use of parentheses. AFAIK there's no way to do that in C.

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by