Plotting Functions using For Loop and If Statements?

조회 수: 15 (최근 30일)
Nicholas Ross
Nicholas Ross 2021년 2월 17일
편집: KALYAN ACHARJYA 2021년 2월 17일
Hey all,
I'm attempting to write a program using a for loop and conditional statements for the following:
I thought this was a very simple assignment but however when I try to implement my code my plot comes up completely blank. This is my first time working with MATLAB so apologies if this is trivial to most of you. Could someone help me understand what I'm doing wrong? Thanks in advance.
Below is my code:
t=0;
x1= ((t.^2)-(2*t)+3);
x2 = (4*cos((2*pi*t)-(pi/8))+3*sin(2*pi*t));
x3 = (sinc(t));
figure(1);
hold on
for i= -4:0.1:4
if (i> - 4) && (i< -2)
t = i;
y = x1;
elseif (i >-2) && (i < 2)
t = i;
y = x2;
elseif (i > 2) && (i< 4)
t = i;
y = x3;
end
plot(t,y)
end

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 2월 17일
편집: KALYAN ACHARJYA 2021년 2월 17일
t=-4:0.1:4
x1= (t.^2)-(2*t)+3;
x2 = 4*cos((2*pi*t)-(pi/8))+3*sin(2*pi*t);
x3 = sinc(t);
y=zeros(1,length(t));
for i=1:length(t)
if (t(i)>-4) && (t(i)< -2)
y(i)= x1(i);
elseif (t(i)>-2) && (t(i) < 2)
y(i)= x2(i);
else
y(i)= x3(i);
end
end
figure,plot(t,y);
Important: Here you can avoid loop and if else condition (recommended), please try once, we are here to help you.
  댓글 수: 4
KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 2월 17일
This is logical indexing, Here the links
https://blogs.mathworks.com/loren/2013/02/20/logical-indexing-multiple-conditions/
https://in.mathworks.com/help/matlab/matlab_prog/techniques-for-improving-performance.html
Nicholas Ross
Nicholas Ross 2021년 2월 17일
Thank you for your help. I really appreciate it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by