Adding an outer for loop for a plot

1 Ansicht (letzte 30 Tage)
Benjamin
Benjamin am 5 Mär. 2019
Kommentiert: Benjamin am 6 Mär. 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

Akzeptierte Antwort

Bob Thompson
Bob Thompson am 5 Mär. 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.

Weitere Antworten (1)

per isakson
per isakson am 5 Mär. 2019
Bearbeitet: per isakson am 5 Mär. 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by