Matlab:如何读取包含带有文本标题的连续(x,y)数值表的数据文件,并绘制数据?

时间:2017-02-06 08:35:38

标签: matlab plot reshape textscan

我的 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 xy 数据中使用图表标题中的数字来读取这些数据,即0.3m, 0.55m 1}}等等。

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

有人可以帮我解决这个问题吗? 非常感谢您的帮助。
最诚挚的问候,
艾玛

1 个答案:

答案 0 :(得分:0)

以下代码可以实现您想要的效果和结果:

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{:});

Plot from text array