loop with subplot in MATLAB

2 visualizzazioni (ultimi 30 giorni)
Teshome Kumsa
Teshome Kumsa il 13 Mag 2022
Commentato: Teshome Kumsa il 13 Mag 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

Risposta accettata

Dave B
Dave B il 13 Mag 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 Commento
Teshome Kumsa
Teshome Kumsa il 13 Mag 2022
Thank you very much. You answered it exaclty.

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by