Adding an outer for loop for a plot

1 view (last 30 days)
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

Accepted Answer

Bob Thompson
Bob Thompson on 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.

More Answers (1)

per isakson
per isakson on 5 Mar 2019
Edited: per isakson on 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!