xlim function error. i have seen on video, the codes were working but with me it is not working

조회 수: 5 (최근 30일)
**My codes are below. I get that error: "Error using xlim (line 31) Limits must be a 2-element vector of increasing numeric values."
Also xtickformat function gives me eror. Can you help me? Thanks**
clc; clear; close all;
dates=datetime(2025,8,17)+calmonths(2:11)+calweeks(0:9)
xlim(datetime([2025 2026],[11 5],[12 23]))
xtickformat('dd-MMM-yyyy')

채택된 답변

dpb
dpb 2021년 6월 29일
You're trying to set axis limits on a numeric axes with datetime values -- no can do...
dates=datetime(2025,8,17)+calmonths(2:11)+calweeks(0:9); % create your date vector
figure % make new figure so is clean
xlim(datetime([2025 2026],[11 5],[12 23])) % try your operation
xtickformat('dd-MMM-yyyy')
Error using xlim (line 31)
Limits must be a 2-element vector of increasing numeric values.
>>
And, as you saw, boom! Because the default axes created is numeric -- and xlim isn't strong enough to change them to a DatetimeRuler object on its own.
>> plot(dates,randn(size(dates))) % plot a datetime object first
>> xlim(datetime([2025 2026],[11 5],[12 23])) % now you can set the limits as wanted
>>
MORAL: Always make sure you've got the right type of axes object first -- with datetime, need to have put some data on the axes first with plot() or other higher-level function to create the proper type.
  댓글 수: 6
Yusuf Suer Erdem
Yusuf Suer Erdem 2021년 7월 2일
Check my codes please, they are working pretty fine.
history=datetime(2019,08,1)+caldays(0:10);
y=randi([11,21],1,11);
stem(history,y,'filled');
tarihBaslangic=datetime(2019,08,1);
tarihBitis=datetime(2019,08,8);
xlim([tarihBaslangic tarihBitis])

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

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 6월 29일
I would expect to see that error if you'd plotted with non-datetime data as your X data. If for example you'd plotted these points:
x = 1:10;
y = x.^2;
plot(x, y)
How much of that plot would you expect to see if I set the X limits from last Thursday to next Saturday?
T = datetime('today');
lastThursday = dateshift(T, 'dayofweek', 'Thursday', 'previous')
lastThursday = datetime
24-Jun-2021
nextSaturday = dateshift(T, 'dayofweek', 'Saturday', 'next')
nextSaturday = datetime
03-Jul-2021
plot(x, y)
xlim([lastThursday, nextSaturday]);
Error using xlim (line 31)
Limits must be a 2-element vector of increasing numeric values.
You haven't specified what error message you received when you tried calling xtickformat but I'm guessing the root cause is the same: you can't change numbers on the X axis into dates and times.

카테고리

Help CenterFile Exchange에서 Specifying Target for Graphics Output에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by