ROGER
ROGER

Reputation: 1

MATLAB- Function definition

How can i plot a function that has different definitions in different time intervals in MATLAB?

For example function is equal to t plus 1 for t in interval minus 1 to zero and equals t in interval zero to 1.We need to do shifting and scaling after defining the function. So please consider it while answering.

I have tried by defining t as an array t = [-2:0.01:2] and f = zeros( length( t ) ) and then finding the positions in f corresponding to its values of t and assigning it values. I have to multiply two signals ( which are shifted and sampled versions of the original signal). The code that i have written is not giving the desired output.

clc
clear
t=(-10:0.01:10);
y=zeros(size(t));
y(t>=-1 & t<=0)=-1*t(t>=-1 & t<=0)-1;
y(t>=0&t<=1)=t(t>=0&t<=1);
y(t>=1&t<=2)=1;
y(t>=2&t<=3)=-1*t(t>=2&t<=3)+3;
subplot(5,1,1);
plot(t,y);
axis([-5 5 -2 2]);
n1=input('enter the shifting parameter-');
n2=input('enter the scaling parameter-');
t=(t+n1)/n2;
subplot(5,1,2);
plot(t,y);
axis([-5 5 -2 2]);
n3=min(t);
n4=max(t);
p=-10:0.01:10;
y1=zeros(size(p));
y1(p>=-2 & p<=-1)=1;
y1(p>=-1&p<=0)=-1;
y1(p>=0&p<=1)=p(p>=0&p<=1)-1;
y1(p>=1&p<=2)=1;
subplot(5,1,3);
plot(p,y1);
axis([-5 5 -2 2]);
m1=input('enter the shifting parameter-');
m2=input('enter the scaling parameter-');
p=(p+m1)/m2;
subplot(5,1,4);
plot(p,y1);
axis([-5 5 -2 2]);
m3=min(p);
m4=max(p);
a1=max(n3,m3);
a2=min(n4,m4);
r=a1:0.01:a2;
y2=zeros(size(r));
y2=y(r<=a2&r>=a1).*y1(r>=a1&r<=a2);
subplot(5,1,5);
plot(r,y2);
axis([-5 5 -2 2]);

Upvotes: 0

Views: 265

Answers (1)

Cheery
Cheery

Reputation: 16214

Not sure what the problem is, but..

t = -1 : 0.01 : 1;
y = zeros(size(t));
y(t < 0)  = t(t < 0) + 1;
y(t >= 0) = t(t >= 0);
plot(t, y);

If you do not want to have a vertical line in the break point...

hold on;
plot(t(t < 0), y(t < 0));
plot(t(t >= 0), y(t >= 0));
hold off;

like this y=-t-1 ; -1 < t < 0 y=t ; 0 < t < 1 y=2 ; 1 < t < 2 I

Just add a new interval

t = -1 : 0.001 : 2;
y = zeros(size(t));
y(t < 0)  = t(t < 0) + 1;
y(t >= 0 & t < 1) = t(t >=0 & t < 1);
y(t >= 1 & t <=2) = 2; 
plot(t, y);

Upvotes: 0

Related Questions