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 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