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 Center および File ExchangeString についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by