使用txt文件中的数据在MATLAB中绘图
我需要从一个文件中读取数据,并用它的数据绘制一个图表。问题是:使用txt文件中的数据在MATLAB中绘图,matlab,file,plot,Matlab,File,Plot,我需要从一个文件中读取数据,并用它的数据绘制一个图表。问题是: (1) 我无法更改文件中数据的格式 (2) 该格式包含我不知道如何处理的信息和字符 这是数据文件的一部分,它是txt格式的: Estation;Date;Time;Temp1;Temp2;Pressure; 83743;01/01/2016;0000;31.9;25.3;1005.1; 83743;01/01/2016;1200;31.3;26.7;1005.7; 83743;01/01/2016;1800;33.1;25.4;
- (1) 我无法更改文件中数据的格式
- (2) 该格式包含我不知道如何处理的信息和字符
Estation;Date;Time;Temp1;Temp2;Pressure;
83743;01/01/2016;0000;31.9;25.3;1005.1;
83743;01/01/2016;1200;31.3;26.7;1005.7;
83743;01/01/2016;1800;33.1;25.4;1004.3;
83743;02/01/2016;0000;26.1;24.2;1008.6;
我想做的是根据Temp1
和Temp2
绘制Date
和Time
,而不用担心压力。第一列也可以忽略。如何将日期
、时间
和时间
提取到和矩阵中,以便绘制它们?到目前为止,我所做的只是:
fileID = fopen('teste.txt','r');
[A] = fscanf(fileID, ['%d' ';']);
fclose(fileID);
disp(A);
它只读取第一个值,83743
fileID = fopen('input.txt','r');
[A] = fscanf(fileID, ['%s' ';']); % read the header line
[B] = fscanf(fileID, '%d;%d/%d/%d;%d;%f;%f;%f;', [8,inf]); % read all the data into B (the date is parsed into three columns)
fclose(fileID);
disp(B');
请注意,%d
读取一个整数(不是双精度),而%f
读取一个浮点数
有关更多详细信息,请参阅。以以下内容为基础:
请注意将日期解析为C
:首先是您以dd-MM-yyyy
格式给出的日期,我将其转换为yyy-MM-dd
的官方标准,然后是您的小时,需要除以100,然后是0
,表示分和秒。当你没有准确的每小时数据时,你可能需要把它们拆开。最后将其转换为正则表达式,用MATLAB进行处理
其结果是:
您可能想尝试一下这种格式,因为它有很多选项,可能会吸引您。您是指数据的图形表示,还是像在代码中那样简单地进行布局?它们有很大的不同,我是说绘图,图形表示。但我相信要这样做,我必须将数据提取到一个矩阵中,对吗?这里没有他想要的图。我们越来越近了。我测试了你的代码…它可以工作,但它只读取前2行,数字有点混乱,比如,日期应该是和整数,但它显示0.0001,例如。浮点数,比如temp显示的是0.0032,而不是31.9。知道为什么会发生这种情况吗?没有绘图,但数据被提取到一个矩阵中,我可以稍后绘图。@Alexandre不是真的,你缺少矩阵上方的
1.0e+04*
。这些是正确的数字。
fileID = fopen('MyFile.txt','r');
A = fscanf(fileID, ['%s' ';']); % read the header line
B = fscanf(fileID, '%d;%d/%d/%d;%d;%f;%f;%f;', [8,inf]); % read all the data into B (the date is parsed into three columns)
fclose(fileID);
B = B.'; % transpose B
% C is just for verification, can be omitted
C = datetime([B(:,4:-1:2) B(:,5)/100zeros(numel(B(:,1)),2)],'InputFormat','yyyy-MM-dd HH:mm:ss');
D = datenum(C); % Get the date in a MATLAB usable format
Titles = strsplit(A,';'); % Get column names
figure;
hold on % hold the figure for multiple plots
plot(D,B(:,6),'r')
plot(D,B(:,7),'b')
datetick('x') % Set a date tick as axis
legend(Titles{4},Titles{5}); % uses titles for legend