Help with for loops
5 views (last 30 days)
Show older comments
Connor Marvell
on 11 Mar 2019
Commented: Connor Marvell
on 11 Mar 2019
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.
0 Comments
Accepted Answer
Adam Danz
on 11 Mar 2019
Edited: Adam Danz
on 11 Mar 2019
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
More Answers (0)
See Also
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!