Help with for loops

5 vues (au cours des 30 derniers jours)
Connor Marvell
Connor Marvell le 11 Mar 2019
Commenté : Connor Marvell le 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.

Réponse acceptée

Adam Danz
Adam Danz le 11 Mar 2019
Modifié(e) : Adam Danz le 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
  1 commentaire
Connor Marvell
Connor Marvell le 11 Mar 2019
Really helpful, that's great, thanks a lot.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by