使用长标题从文本文件中读取数据

时间:2015-02-02 11:16:35

标签: matlab file-io

我正在尝试将以下文本文件读入MATLAB:

Data from RamanShift_18-24-54-814.txt Node  
Date: Sun Feb 01 18:24:54 GMT 2015  
User:   
Spectrometer: QEP00413  
Autoset integration time: false 
Trigger mode: 4 
Integration Time (sec): 1.000000E0  
Scans to average: 1 
Electric dark correction enabled: true  
Nonlinearity correction enabled: false  
Boxcar width: 0 
XAxis mode: Wavelengths 
Stop averaging: false   
Number of Pixels in Spectrum: 1044  
-66.286 -2.5
-62.486 -0.5
-58.689 -0.5
-54.895 2.5
-51.104 40.5
-47.316 49.5
-43.531 52.5

我想忽略开头的文本并加载两个数字列。我试过这个:

M = dlmread('RamanShift_18-24-54-814.txt','\t',190,0);

此操作失败并出现以下错误:

Error using dlmread (line 139)
Mismatch between file and format string.
Trouble reading number from file (row 2u, field 1u) ==> \n

如果我只选择第二列,请按:

M = dlmread('RamanShift_18-24-54-814.txt','\t',190,1);

然后这可行,但M的每个其他元素都是零?

1113.50000000000
0
1104.50000000000
0
1094.50000000000
0
1069.50000000000
0

1)如何改进这一点以读取两列和2)以纠正备用零问题?

非常感谢, Ť

2 个答案:

答案 0 :(得分:2)

您正在寻找importdata功能

A = importdata('yourTextfile.txt','\t',14)

此行会根据需要跳过文件的第一行 14 行,并使用制表符分隔符读入两个数据列。

答案 1 :(得分:0)

使用textscan,默认使用空格作为分隔符。它将在您的情况下完美运行:

fid = fopen('yourFileName.txt');
resCell = textscan(fid, '%s'); resCell = resCell{1};
fclose(fid);

然后,您可以搜索始终显示在文件中的关键字(如“Spectrum:”)并阅读数字:

startInd = find(strcmpi(resCell, 'Spectrum:'), 1) + 2; % 2 is a shift that you specify that depends in the keyword you chose.

现在:

nSamples = (numel(resCell) - ind + 1)/2; % this should be an even number in your case! I guess that this change between sampling sessions...

data = reshape(str2double(resCell(startInd:end)), 2, nSamples);

最后但同样重要的是,玩得开心!