Adding an outer for loop for a plot

1 回表示 (過去 30 日間)
Benjamin
Benjamin 2019 年 3 月 5 日
コメント済み: Benjamin 2019 年 3 月 6 日
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 件のコメント
Benjamin
Benjamin 2019 年 3 月 6 日
thanks it works!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by