loop with subplot in MATLAB

조회 수: 3 (최근 30일)
Teshome Kumsa
Teshome Kumsa 2022년 5월 13일
댓글: Teshome Kumsa 2022년 5월 13일
I have data sets in the cell. Then I want to deal with those data sets. I have included my sample code here below. I want to plot acceleration, velocity, and displacement for each data set. This code partially worked for the last subplot, and I see only the acceleration plot for the others. Help, please.
acceleration={[10;12;14] [6;8;9] [8;12;18]};
t=[1;2;3];
N=3;
for i=1:N
figure
subplot(3,1,1)
plot(t,acceleration{1,i},'-b')
end
velocity = cell(1,N);
for i=1:N
velocity{1,i}= cumtrapz(t,acceleration{1,i});
subplot(3,1,2)
plot(t,velocity{1,i},'-g')
end
displacement = cell(1,N);
for i=1:N
displacement{1,i}= cumtrapz(t,velocity{1,i});
subplot(3,1,3)
plot(t,displacement{1,i},'-r')
end

채택된 답변

Dave B
Dave B 2022년 5월 13일
The first loop creates a figure for each cell, but the next too loops don't. Did you want a figure for each cell?
acceleration={[10;12;14] [6;8;9] [8;12;18]};
t=[1;2;3];
N=3;
for i=1:N
figure(i)
subplot(3,1,1)
plot(t,acceleration{1,i},'-b')
end
velocity = cell(1,N);
for i=1:N
figure(i)
velocity{1,i}= cumtrapz(t,acceleration{1,i});
subplot(3,1,2)
plot(t,velocity{1,i},'-g')
end
displacement = cell(1,N);
for i=1:N
figure(i)
displacement{1,i}= cumtrapz(t,velocity{1,i});
subplot(3,1,3)
plot(t,displacement{1,i},'-r')
end
Alternatively, shorten the code to do this in one loop:
acceleration={[10;12;14] [6;8;9] [8;12;18]};
t=[1;2;3];
N=3;
for i=1:N
velocity{1,i}= cumtrapz(t,acceleration{1,i});
displacement{1,i}= cumtrapz(t,velocity{1,i});
figure(i)
subplot(3,1,1)
plot(t,acceleration{1,i},'-b')
subplot(3,1,2)
plot(t,velocity{1,i},'-g')
subplot(3,1,3)
plot(t,displacement{1,i},'-r')
end
Even better, use tiledlayout/nexttile instead of subplot!
acceleration={[10;12;14] [6;8;9] [8;12;18]};
t=[1;2;3];
N=3;
for i=1:N
velocity{1,i}= cumtrapz(t,acceleration{1,i});
displacement{1,i}= cumtrapz(t,velocity{1,i});
figure(i)
tiledlayout(3,1)
nexttile(1)
plot(t,acceleration{1,i},'-b')
nexttile(2)
plot(t,velocity{1,i},'-g')
nexttile(3)
plot(t,displacement{1,i},'-r')
end
  댓글 수: 1
Teshome Kumsa
Teshome Kumsa 2022년 5월 13일
Thank you very much. You answered it exaclty.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by