Using plot with dates stored in a cell array

Hello Matlab experts,
I need your help plotting a price of some item on different days.
I have a cell array called dates with dates stored as strings (actually char) in the follwoing format: '1/22/20'
I also have an array of double with prices called prices. Lengths of these two arrays are of course identical. Now, I would like to plot the prices on different dates (as bars). If I use datetime, the date is converted to the year 0020. So,how to use plot function to plot dates on x axis and prices on y axis? Thank you very much.
>> class (dates{1})
ans =
char
>> datetime(dates{1})
ans =
22-Jan-0020
>> dates{1}
ans =
1/22/20

 채택된 답변

Star Strider
Star Strider 2022년 5월 6일
I get a different result —
i = 1;
dates{i} = '1/22/20';
dtv = datetime(dates{i}, 'InputFormat','MM/dd/yy')
dtv = datetime
22-Jan-2020
That appears to be correct.
This should lalso work in recent versions of MATLAB. See Date and Time from String Array for details.
.

추가 답변 (2개)

Voss
Voss 2022년 5월 6일
Here's one way to add 2000 to the years
dates = {'1/22/20','1/23/20','1/24/20','1/25/20'};
new_dates = datetime(regexprep(dates,'\d+$','${sprintf(''%d'',str2double($0)+2000)}'))
new_dates = 1×4 datetime array
22-Jan-2020 23-Jan-2020 24-Jan-2020 25-Jan-2020
Then you can use them in plot or bar or whatever.
prices = [100 101 98 94];
bar(new_dates,prices)
hold on
plot(new_dates,prices,'-ro','LineWidth',2)
Askic V
Askic V 2022년 5월 6일

0 개 추천

Thank you, I didn't know how to call datetime function properly. 'InputFormat','MM/dd/yy' is the answer I was looking for.
dates =
1×5 cell array
{'1/21/20'} {'1/22/20'} {'1/23/20'} {'1/24/20'} {'1/25/20'}
>> datetime(dates)
ans =
1×5 datetime array
21-Jan-0020 22-Jan-0020 23-Jan-0020 24-Jan-0020 25-Jan-0020
>> dtv = datetime(dates, 'InputFormat','MM/dd/yy')
dtv =
1×5 datetime array
21-Jan-2020 22-Jan-2020 23-Jan-2020 24-Jan-2020 25-Jan-2020

댓글 수: 2

Voss
Voss 2022년 5월 6일
Well, that's certainly easier than my solution!
Askic V
Askic V 2022년 5월 6일
Yes, but your solution is really very creative.

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

카테고리

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

질문:

2022년 5월 6일

댓글:

2022년 5월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by