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

2 views (last 30 days)
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 Comment
dpb
dpb on 14 Mar 2014
Edited: dpb on 14 Mar 2014
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.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!