# How can I create a plot with subplots in a loop?

조회 수: 4 (최근 30일)
gsourop 2019년 7월 10일
댓글: Bobby Huxford 2019년 7월 10일
Hi everyone,
I am trying to create a plot with subplots within a loop. The code so far is:
x = randn(100,13);
D = 1966
dis = 3
[T N] = size(x);
for i = 1 : N
VARNAMES{i} = i;
end
time = datetime(D,1:T,1);
figure;
for k = 1:N
subplot (ceil(N/dis),dis,k)
filename = plot( time' , x(:, k ) );
xlim(datenum([min(time) max(time)]))
title ( VARNAMES(k));
hold on
end
But I get an Error message ''Error using xlim (line 31)
Limits must be a 2-element vector of increasing datetime values.''
Could you please point out where is the mistake?
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Bobby Huxford 2019년 7월 10일
The issue seems to be with xlim(), rather than with creating subplots within a loop.
If you remove the below line, subplots are created within a loop.
xlim(datenum([min(time) max(time)]))
However, you can use the xlim command in this code by removing the datenum function:
x = randn(100,13);
D = 1966
dis = 3
[T N] = size(x);
for i = 1 : N
VARNAMES{i} = i;
end
time = datetime(D,1:T,1);
figure;
for k = 1:N
subplot (ceil(N/dis),dis,k)
filename = plot( time' , x(:, k ) );
xlim([min(time) max(time)])
title ( VARNAMES(k));
hold on
end

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

### 채택된 답변

Geoff Hayes 2019년 7월 10일
gsourop - why the conversion at
datenum([min(time) max(time)])
since time should already be an array of datenum types? You may just need to do
xlim([min(time) max(time)])
so that you pass a two-element vector of increasing values.
Also, you should rename your time array so that it doesn't conflict with the built-in MATLAB function of the same name (see time for details).

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

### 카테고리

Help CenterFile Exchange에서 Subplots에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by