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

2 次查看(过去 30 天)
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 中查找有关 Text Data Preparation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by