【问题标题】:Matlab: How to read data file containing sequential (x,y) numerical tables with text titles, and plot the data?Matlab:如何读取包含带有文本标题的顺序(x,y)数值表的数据文件,并绘制数据?
【发布时间】:2017-02-06 08:35:38
【问题描述】:

我有 x-y 数据存在于一个文本文件中,如下所示:

(("height-0.3m")    
-0.0527942  0.0595315
-0.0525685  0.0594241
)

(("height-0.55m")   
-0.0527939  0.0263362
-0.0525683  0.0265083
)

(("height-0.83m")
-0.0528517  0.233493
-0.0526329  0.231228
)

我想读取MATLABplot 中的这些数据x-y 数据使用图表图例的表格标题中的数字,即0.3m, 0.55m 等。

数据为space-delimited,表格有任意行数,但表格始终包含在括号中,并且每个表格的末尾都有一个空行。

谁能帮我解决这个问题?
非常感谢您的帮助。
最好的问候,
艾玛

【问题讨论】:

    标签: matlab plot reshape textscan


    【解决方案1】:

    这是实现您想要的代码和结果图:

    clear; clc;
    
    %% Initialize variables.
    filename = 'C:\Users\UserName\FileLocation\data.txt';
    delimiter = {'((',' ',')'};
    
    %% Read columns of data as strings:
    % For more information, see the TEXTSCAN documentation.
    formatSpec = '%q%q%[^\n\r]';
    
    %% Open the text file.
    fileID = fopen(filename,'r');
    
    %% Read columns of data according to format string.
    % This call is based on the structure of the file used to generate this
    % code. If an error occurs for a different file, try regenerating the code
    % from the Import Tool.
    dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true,  'ReturnOnError', false);
    
    %% Close the text file.
    fclose(fileID);
    
    
    data = repmat({''},length(dataArray{1}),2);
    for col=1:length(dataArray)-1
        data(1:length(dataArray{col}),col) = dataArray{col};
    end
    
    % Plotting each height value
    PlotMatrix = [];
    leg = {};
    for k = 1:length(data(:,2))
        if strcmp(data{k,1}(1:6),'height') 
            leg{end+1,1} = data{k,1};
            if ~isempty(PlotMatrix)
                figure(1)
                hold on
                plot(PlotMatrix(:,1), PlotMatrix(:,2))
                hold off
            end
            PlotMatrix = [];
        else
            PlotMatrix = [PlotMatrix; [str2double(data{k,1}), str2double(data{k,2})]];
        end
    end
    
    % Plot last matrix
    if ~isempty(PlotMatrix)
        figure(1)
        hold on
        plot(PlotMatrix(:,1), PlotMatrix(:,2))
        hold off
    end
    
    legend(leg{:});
    

    【讨论】:

    • 非常感谢您的努力。该解决方案几乎可以工作,但我仍然有一些我自己无法解决的问题。首先,数据似乎是制表符分隔而不是空格分隔(使用 Excel 的错误 :) 然后,我实际上已经意识到表格标题分为 x 数据的标题和 y 数据的标题,但在示例中我前提是我为了简化而对其进行了修改。所以原始问题中的第一个表看起来完全像这样:((xy/key/label "h-0.3m") -0.0527942 0.0595315 -0.0525685 0.0594241 )
    • 建议你看一下导入工具。在Home 选项卡上,单击Import Data。您可以使用这些设置,然后在Import Selection 下拉列表中生成代码。此代码通常可以简化,因此请尝试不同行的功能。至于制表符分隔,只需将其添加到分隔符列表中,'\t'? uk.mathworks.com/help/matlab/ref/…
    • 另外,当格式开始变得像您的第一条评论一样复杂时,请编辑问题以添加详细信息,否则事情很快就会变得不清楚。
    • 当我运行代码时,dataArray 中的数字会相互连接,例如:-0.05279420.0595315 输出图应该与您提供的图表一样,即没有 x-data 标题,但是带有 y 数据标题!
    • 你在使用str2double吗?您是否完全按照上面的方式运行代码,但使用您自己的文件路径?