How to import data from external file to Matlab when a format repeats N times inside the file?

3 ビュー (過去 30 日間)
Dear all,
I have a lot of files with the following format inside:
First Line: title; Second line: subtitle; then, a MxN matrix.
Example:
# Detector n: 1 Det1Name (integrated over solid angle)
# N. of energy intervals 500
1.000E-06 1.030E-06 0.000E+00 0.000E+00
1.030E-06 1.061E-06 1.000E+00 0.000E+00
1.061E-06 1.094E-06 0.000E+00 0.000E+00
1.094E-06 1.127E-06 3.000E+00 0.000E+00
1.127E-06 1.161E-06 4.000E+00 0.000E+00
1.161E-06 1.196E-06 2.000E+00 0.000E+00
1.196E-06 1.232E-06 1.000E+00 0.000E+00
(...)
# Detector n: 2 Det2Name (integrated over solid angle)
# N. of energy intervals 500
1.000E-06 1.030E-06 0.000E+00 0.000E+00
1.030E-06 1.061E-06 1.00E+01 0.000E+00
1.061E-06 1.094E-06 3.000E+01 0.000E+00
1.094E-06 1.127E-06 9.000E+00 0.000E+00
1.127E-06 1.161E-06 1.200E+00 0.000E+00
1.161E-06 1.196E-06 1.400E+00 0.000E+00
1.196E-06 1.232E-06 1.200E+00 0.000E+00
(...)
(...)
So, How to import this file to MATLAB in order to get matrix like Det1(M,N), Det2(M,N), etc?
If I had just one table for each file, I could use importdata(). But, what about this case?

採用された回答

Titus Edelhofer
Titus Edelhofer 2015 年 11 月 25 日
Hi,
you can use textscan for this task:
% open the file
fid = fopen('yourfile.txt', 'rt');
% read the first header line, discard or do what ever you like with it
firstHeader = fgetl(fid);
% read the second header line and get the number of rows:
secondHeader = fgetl(fid);
tokens = textscan(secondHeader, '%s');
rows = str2double(tokens{1}{end});
% read the data
aData = textscan(fid, '%g', 4*rows);
data = reshape(aData{1}, 4, rows)';
and then you continue to do this in a loop (with result data{iLoop} = reshape(aData...) until you reach the end of the file (e.g. firstHeader is 0 instead of a string.
Titus
  1 件のコメント
Marlon Saveri Silva
Marlon Saveri Silva 2015 年 11 月 25 日
Titus,
Thank you too much; perfect answer; it would take me days to find it by myself

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLarge Files and Big Data についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by