Using for loop to plot multiple plots on the same graph

5 views (last 30 days)
RPS19 on 2 Apr 2021
Commented: RPS19 on 2 Apr 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
hold on
end % end if
hold off
legend('Tau1 1e-3', 'Tau1 1e-4', 'Tau1 1e-5')
grid on
title('System Bode Plots')

Accepted Answer

DGM on 2 Apr 2021
Edited: DGM on 2 Apr 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
hold on
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]);
% 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);
hold off
legend(legendstrings,'location','northwest') % you can just set the location as needed
grid on
title('System Bode Plots')
  1 Comment
RPS19 on 2 Apr 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.

Sign in to comment.

More Answers (1)

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

Community Treasure Hunt

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

Start Hunting!