2014-07-26 65 views
0

我是Matlab新手,我有一个如下所示的文本文件。将文本文件的某些部分导入到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 

.......... 
+1

你想让一行中的每个元素占据矩阵中的一个位置,或者每行占据一个位置吗?例如,第1行中的0和1会占据位置(1,1)和(1,2)?我问,因为你可能想使用单元阵列而不是矩阵。 –

回答

0

编辑指定了什么,他希望:)

第一13线可以调用textscan时,根据official documentation使用选项HeaderLines被跳过OP之后的ANSWER。

假设文件是​​由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。有关format的更多信息在official docs

+1

感谢您的回答,我需要的是一个4x2矩阵,我想跳过您的indata结果的前三行,我也可能不会很清楚地解释这一点。 – s900n

+0

谢谢你更好地解释你的需求。我编辑了我的答案,现在它应该适合目的! – lucam

+0

我想问你的一些最后一件事我没有像我的例子那样在两行之间有空行。当我将这个代码应用于indata结果时,两个数字组合并且输出给出错误。你能帮忙吗?谢谢。 – s900n

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' 

,其中每一行包含字符串。然后,您可以随时随地调整结果,以便随心所欲地构建矩阵/单元阵列。希望有所帮助!