THIS is a little problem which is mostly faced by Students in MATLAB coding that How to write code for this type of function (Piecewise).
when we write a code for the given code we will convert this one function into three parts.
1. Less then A (-0.5):
Just write the code as
x = [-1:0.1:1];
for i = 1:1:21
if (x(i)) < -0.5)
y(i) = 0
end
end
2. Grater then B (0.5):
and write the code for x > 0.5
x = [-1:0.1:1];
for i = 1:1:21
if (x(i)) > 0.5)
y(i) = 1
end
end
3. Between A to B:
and here is little bit complex to find A to B Slop equation.
A point is at (x = -0.5 , y = 0) and B is at (x = 0.5 , y = 1)
then
Line equation format is y = m.x + c
m is the slope of the line in equation which is = (Delta (y)/ Delta (x)) or (YB - YA) / (XB - XA)
which is in this case
m = {1 - 0} / {0.5 - (-0.5)}
m = 1
and equation format is (YB - YA) = m (XB - XA)
here A is start point which we know (-0.5, 0) and finding next point toward B so
YB replace as just Y and XB with X that is unknown point
Y - 0 = 1 * (X + 0.5)
so the Y = X + 0.5
if x = -0.5 then y = 0
as shown in above graph
m = 1;
x = [-1:0.1:1];
for i = 1:1:21
else
y(i) = m * x(i) + 0.5;
end
end
IN THIS CASE:
A point is at (x = -0.5 , y = -1) and B is at (x = 0.5 , y = 1)
Y - (-1) = 2 * (X + 0.5)
Y+1 = 2 * X +1
so the Y = 2 * X
if x = -0.5 then y = -1
as shown in above graph
m = 2;
x = [-1:0.1:1];
for i = 1:1:21
else
y(i) = m * x(i);
end
end
Great...
ReplyDelete