How to import data from external file to Matlab when a format repeats N times inside the file?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Marlon Saveri Silva
el 25 de Nov. de 2015
Comentada: Marlon Saveri Silva
el 25 de Nov. de 2015
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?
0 comentarios
Respuesta aceptada
Titus Edelhofer
el 25 de Nov. de 2015
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Large Files and Big Data en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!