loop with subplot in MATLAB

1 回表示 (過去 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 Center および File ExchangeSubplots についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by