Plotting Functions using For Loop and If Statements?
14 views (last 30 days)
Show older comments
Nicholas Ross
on 17 Feb 2021
Edited: KALYAN ACHARJYA
on 17 Feb 2021
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 Comments
Accepted Answer
KALYAN ACHARJYA
on 17 Feb 2021
Edited: KALYAN ACHARJYA
on 17 Feb 2021
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 Comments
KALYAN ACHARJYA
on 17 Feb 2021
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
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!