# loop with subplot in MATLAB

1 vue (au cours des 30 derniers jours)
Teshome Kumsa le 13 Mai 2022
Commenté : Teshome Kumsa le 13 Mai 2022
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
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Dave B le 13 Mai 2022
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 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Teshome Kumsa le 13 Mai 2022
Thank you very much. You answered it exaclty.

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Subplots dans Help Center et File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by