Using for loop to plot multiple plots on the same graph

92 vues (au cours des 30 derniers jours)
RPS19
RPS19 le 2 Avr 2021
Commenté : RPS19 le 2 Avr 2021
I am trying to plot 3 plots on the same graph , I believe the best way to do this would be a for loop. I'd like to keep the paramaters that I am changing flexible, so I would like to call them from an array. This is the code that I have so far, where 'Tau1' is a parameter that varies the function 'G_fun'. I am only getting one plot which the legend is labelling to be the last plot with Tau1 = 1e-5. How would I be get a different plot of G_fun for each value of Tau1 on the same graph? Thank you in advance for any help.
N = [1e-3,1e-4,1e-5];
for i = 1:1:3
Tau1 = N(i); % the parameter to be changed
if N(i) == 1e-3
figure
hold on
end % end if
bode(G_fun);
end
hold off
legend('Tau1 1e-3', 'Tau1 1e-4', 'Tau1 1e-5')
grid on
title('System Bode Plots')
  1 commentaire
DGM
DGM le 2 Avr 2021
What is G_fun? How is it getting the parameter Tau1?

Connectez-vous pour commenter.

Réponse acceptée

DGM
DGM le 2 Avr 2021
Modifié(e) : DGM le 2 Avr 2021
I'm going to guess the primary issue is with your function not getting access to the changing parameter, but let's just show that it does work. There are a few things that can be improved:
% i just changed these to suit my example TF
N = [2e-1,1e-1,1e-2];
% you can just move this outside the loop to avoid the conditional
figure
hold on
legendstrings=cell(size(N));
for i = 1:length(N) % make stuff independent of array sizes
Tau1 = N(i);
% idk what your TF is or how tau is used in it
% this is just some garbage i made as an example
H = tf([1 0.1 7.5*(1-Tau1)],[1 0.12 9 0 0]);
bode(H)
% build the legends from the parameters themselves
% instead of using literal strings that might be wrong if N changes
legendstrings{i}=sprintf('Tau1 = %2.2e',Tau1);
end
hold off
legend(legendstrings,'location','northwest') % you can just set the location as needed
grid on
title('System Bode Plots')
  1 commentaire
RPS19
RPS19 le 2 Avr 2021
Thank you! This is a much better way of doing it, much more flexible which is what I needed. The problem was with my function not getting access to the variables. I had G_fun = G(a,b,c,Tau1) where G() is my actual transfer function. When I inputted G() instead of G_fun within the for loop it worked perfectly, although I don't completely understand why.

Connectez-vous pour commenter.

Plus de réponses (1)

William Rose
William Rose le 2 Avr 2021
Try putting the figure command and the hold on command outside and before the for loop.

Catégories

En savoir plus sur Graphics Performance dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by