Plotting Functions using For Loop and If Statements?

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

请先登录,再进行评论。

更多回答(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