Help with for loops

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops 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