Effacer les filtres
Effacer les filtres

Adding an outer for loop for a plot

1 vue (au cours des 30 derniers jours)
Benjamin
Benjamin le 5 Mar 2019
Commenté : Benjamin le 6 Mar 2019
I have the following code:
eta = 0.4;
eta_c = 0.6;
rpf = eta/eta_c;
count = 0;
for x = 1:0.01:1.5
count = count + 1;
z(count) = g(x,rpf);
end
x= 1:0.01:1.5;
plot(x,z,'-')
grid on;
It does what I want. My question though is, how can I do an outer loop to also loop over eta? What if I want to have different values of eta, but not in any incremental order (4.0, 4.2, 4.7) etc. and then plot them all on the same graph with a hold on or something? Anyone know how I can do this? Assume my function is correct that is called

Réponse acceptée

Bob Thompson
Bob Thompson le 5 Mar 2019
eta = [5.4 6.7 5.2];
hold on
for i = 1:length(eta);
eta_c = 0.6;
rpf = eta(i)/eta_c;
count = 0;
for x = 1:0.01:1.5
count = count + 1;
z(count) = g(x,rpf);
end
plot([1:0.01:1.5],z,'-')
grid on;
end
You could have a very similar loop for eta_c if you want to vary those values as well.
I changed your plot x values because while defining x works for when you just have the one loop, it would be better not to keep changing the size and value within the outer loop. It shouldn't directly cause a problem, but better safe than sorry.
  1 commentaire
Benjamin
Benjamin le 6 Mar 2019
thanks it works!

Connectez-vous pour commenter.

Plus de réponses (1)

per isakson
per isakson le 5 Mar 2019
Modifié(e) : per isakson le 5 Mar 2019
This is may approach. (Don't change the code that works.)
function cssm( )
eta = [ 4.0, 4.2, 4.7 ];
for e = eta
cssm_( e )
hold on
end
end
function cssm_( eta )
eta_c = 0.6;
rpf = eta/eta_c;
count = 0;
for x = 1:0.01:1.5
count = count + 1;
z(count) = g(x,rpf);
end
x = 1:0.01:1.5;
plot(x,z,'-')
grid on;
end
function out = g( x, rpf )
out = x + rpf;
end
It works but the hold-part asks for improvement. Then refine the code if (and only if) it's needed.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by