【问题标题】:Import certain part of textfile to matlab将文本文件的某些部分导入matlab
【发布时间】:2014-09-18 06:17:37
【问题描述】:

我是 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 行中的 0 和 1 会占据位置 (1,1) 和 (1,2) 吗?我问是因为您可能想使用元胞数组而不是矩阵。

标签: matlab file file-io io


【解决方案1】:

如果你试试这个:

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'

其中每一行都包含一个字符串。然后,您可以随意使用结果来构建矩阵/单元阵列。希望对您有所帮助!

【讨论】:

    【解决方案2】:

    在 OP 更准确地指定他想要的内容之后编辑答案:)

    在调用textscan时,可以使用选项HeaderLines跳过前13行,与official documentation一致。

    假设文件是​​ 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 数字,它只是四舍五入到小数点后四位。如果您想查看完整的输出,只需发出format long。有关format 的更多信息,请访问official docs

    【讨论】:

    • 感谢您的回答,我实际上需要的是一个 4x2 矩阵,我也想跳过您的 indata 结果的前 3 行,我可能不太清楚解释这一点。
    • 感谢您更好地解释您的需求。我编辑了我的答案,现在它应该适合目的!
    • 最后一件事我想问你一些我没有像我的例子那样两行之间有空行的数据。当我将此代码应用到数据结果中作为两个数字组合时,输出给出错误。你也可以帮忙吗。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多