Having trouble graphing multiple subplots while using a for loop. Please help! Much appreciated

I need to plot a equation for a few different values of n with x in a specific range. I need to plot these on three seperate subplots while using a for loop. This is what I have so far:
n=[4 2 1];
x=-5:5;
y=0
hold on
for k=1:length(n);
for j=1:length(x)
y=n(k).*cos(x(j));
subplot(1,3,k);
plot(x,y,'-Xb');
end
end
The only issue is that I keep getting a single constant value for y for each of my plots? How do I get the graphs to come out correctly?
Any help is much appreciated. Thanks!

回答 (1 件)

Stephen23
Stephen23 2016 年 7 月 13 日
編集済み: Stephen23 2016 年 7 月 13 日
You have created too many loops. Only the outer loop in needed, the inside one should be replaced by a simple vectorized operation:
n = [4,2,1];
x = -5:5;
for k = 1:length(n);
y = n(k).*cos(x);
subplot(1,3,k);
plot(x,y,'-xb');
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2016 年 7 月 13 日

編集済み:

2016 年 7 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by