Help with for loops

5 ビュー (過去 30 日間)
Connor Marvell
Connor Marvell 2019 年 3 月 11 日
コメント済み: Connor Marvell 2019 年 3 月 11 日
I'm really new to MATLAB so I apologise in advance for my simple question. But I'm trying to construct a plot of 5 different sine waves, & my code looks like this:
x=0:pi/100:2*pi;
y1=sin(x);
plot(x,y1);
hold on
y2=sin(2*x);
plot(x,y2)
y3=sin(3*x);
plot(x,y3)
y4=sin(4*x);
plot(x,y4)
y5=sin(5*x);
plot(x,y5)
I'd like to learn how to tidy this up a bit by using a loop in place of manually adding each next sine wave, but I can't figure out how for the life of me, & would really appreciate some help or advice.

採用された回答

Adam Danz
Adam Danz 2019 年 3 月 11 日
編集済み: Adam Danz 2019 年 3 月 11 日
Here are three options in order of best-practice. They all produce the same plot. Feel free to ask any follow-up questions.
%% Option 1: don't use a loop at all
x = 0 : pi/100 : 2*pi; % produce your x-data (vector)
w = 1:5; % these are your factors (vector)
y = sin(w' * x); % produce your y data; note the transpose (') (matrix)
plot(x,y) % Plot the data
%% Option 2: collect data within loop, then plot it.
x = 0 : pi/100 : 2*pi;
w = 1:5;
yMat = zeros(length(x), length(w)); %produce an empty matrix where we'll store loop data
for i = 1:length(w) %Loop through each factor
yMat(:,i) = sin(w(i) * x); %store the y-data
end
plot(x, yMat)
%% Option 3: plot data within loop
x = 0 : pi/100 : 2*pi;
w = 1:5;
figure;
axh = axes; %create the empty axes
hold(axh, 'on') %hold the axes
for i = 1:length(w)
y = sin(w(i) * x); % produce temporary y-data
plot(axh, x,y) % plot the single line
end
  1 件のコメント
Connor Marvell
Connor Marvell 2019 年 3 月 11 日
Really helpful, that's great, thanks a lot.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by