Plotting Functions using For Loop and If Statements?

15 vues (au cours des 30 derniers jours)
Nicholas Ross
Nicholas Ross le 17 Fév 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

Réponse acceptée

KALYAN ACHARJYA
KALYAN ACHARJYA le 17 Fév 2021
Modifié(e) : KALYAN ACHARJYA le 17 Fév 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 commentaires
KALYAN ACHARJYA
KALYAN ACHARJYA le 17 Fév 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
Nicholas Ross
Nicholas Ross le 17 Fév 2021
Thank you for your help. I really appreciate it.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by