I'm trying to plot my data with time on the x-axis. My data has the following csv format:
13:05:48 1.33 5.15
13:05:53 2 5.2
13:05:58 2.1 4.88
There are 3 columns with column 1 being my time(HH:MM:SS) and column 2 and 3 being my data. How do I read then plot Column 1 time vs. my column 2 or 3?

 채택된 답변

dpb
dpb 2015년 8월 18일
편집: dpb 2015년 8월 20일

0 개 추천

[d,x,y]=textread('ivan.csv','%8s %f %f','delimiter',' ');
dn=datenum(d,'HH:MM:SS'); % ERRATUM: had lowercase in time format string
plot(dn,[x y])
datetick('x')
Alternatively, use textscan or with the latest releases there's a new datetime object

댓글 수: 3

Ivan Q
Ivan Q 2015년 8월 18일
I was getting some errors so I rewrote the code to this:
fid = fopen( 'file.txt' );
A=textscan(fid,'%8s %f %f');
x=A{2};
y=A{3};
dn=datenum(A{1},'hh:mm:ss');
plot(dn,y)
datetick('x','HH:MM:SS')
However, dn cycles between values of 7.3706 and 7.3606 and my x-axis does not show up as a time. How do I get the X-axis to display my exact time strings ie. 13:58:38
Ivan Q
Ivan Q 2015년 8월 19일
I was able to accomplish what I wanted with the following code:
%%Open data and separate cells
fid = fopen( 'Data.txt' );
A=textscan(fid,'%8s %f %f');
x=A{2};
y=A{3};
dn=datenum(A{1},'HH:MM:SS'); %change string into datenum
%%plot figure
plot(dn,x*2)
hold on
plot(dn,y)
%%Set x-axis
l=length(dn)
set(gca, 'XTick', (dn(1) : .001 : dn(l)) )
datetick('x','HH:MM:SS','keepticks')
dpb
dpb 2015년 8월 20일
Ah, yes, I carelessly used lower case for the time fields in the format string; that's an error, sorry. Checked that the textread worked right but didn't actually look a the the returned times on the axes, only that they were actually formatted as dates...I fixed up the Answer altho you've uncovered the problem.
I tend to use textread where I can even though it has been relegated to "red-haired stepchild" status by TMW as it doesn't require the extra step of fopen/fclose and returns char and double arrays where don't need or want cell arrays. It does require a separate variable for each field which can be a nuisance and can't handle all cases that textscan can, but for simple file structures it's a better option imo still. Anyway, that's an aside not related to the actual problem here...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Annotations에 대해 자세히 알아보기

태그

질문:

2015년 8월 18일

편집:

dpb
2015년 8월 20일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by