我是Matlab的新手,我有一个类似下面的文本文件。
我想忽略带有文字的前7行,然后以矩阵形式导入其余部分。感谢帮助。
5.7.2014 20:01:30
C:\Users\s\Desktop
C:\Users\s\Desktop
Activation
0,1
20,20,0 255,255,0 137,137,0
0
0 0,104797
0 0,104798
0 0,104799
0 0,104798
..........
答案 0 :(得分:0)
如果您尝试这样做怎么办:
clear
clc
fileID = fopen('TestFile.rtf'); % I copied you file in a dummy document.
txt = fscanf(fileID,'%c');
Data = textscan(txt,'%[^\n]','delimiter','\n'); % look for line changes (sorry I don't remember the real name for this)
YourData = cell(7,1);
for p = 12:18 % specific for your document. You can make it more general of course
k = p-11;
YourData{k} = Data{1}{p};
YourData{k} = regexprep(YourData{k},'\\',''); % remove the \ if there are any
end
disp(YourData)
给出了这个:
'0,1'
'20,20,0 255,255,0 137,137,0'
'0'
'0 0,104797'
'0 0,104798'
'0 0,104799'
'0 0,104798'
其中每一行都包含一个字符串。然后,您可以根据需要使用结果来构建矩阵/单元格数组。希望有所帮助!
答案 1 :(得分:0)
在OP明确指出之后编辑回答:)
根据official documentation调用HeaderLines
时,可以使用选项textscan
跳过前13行。
假设该文件是OP提供的文件,然后将其称为test.txt
,则以下代码将执行此操作。
% read the text file original text file
orig = fileread('test.txt');
% replace commas with dots
newfile = strrep(orig,',','.');
% create a new text file in write mode
fid_w = fopen('test_mod.txt','w')
% write this modified version of the file to disk
fprintf(fid_w,'%s',newfile);
% close this text file
fclose(fid_w)
% open the modified text file in read mode
fid_r = fopen('test_mod.txt','r');
% put the data in a cell array, assuming strings and skipping the
% first 13 lines
indata = textscan(fid_r, '%s', 'HeaderLines',13, 'Delimiter', '\r');
% close the modified text file
fclose(fid_r);
% cell --> char
indata = cell2mat(indata{1});
% char --> number
indata = str2num(indata)
这应该是所寻求的输出:
indata =
0 0.1048
0 0.1048
0 0.1048
0 0.1048
我也在发布whos indata
的输出:
Name Size Bytes Class Attributes
indata 4x2 64 double
哦,当然indata
包含整个0.104797
数字,它只是舍入到4位小数。如果您希望查看完整输出,请发出format long
。有关official docs中的format
的更多信息。