Adding an outer for loop for a plot

1 次查看(过去 30 天)
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

采纳的回答

Bob Thompson
Bob Thompson 2019-3-5
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 个)

per isakson
per isakson 2019-3-5
编辑:per isakson 2019-3-5
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by