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
0 个评论
采纳的回答
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
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!