Anoop Kanyan
Anoop Kanyan

Reputation: 618

Plot unit step using if else conditions

i am using this code to plot unit step function

t1=-2:0.01:2;

if t1>=0
    y=1;
else if t1<0
    y=0;

   end

end

subplot(3,1,1)
plot(t1,y)`

but i dont get the desired output.It is plotting zero for y at every point.

Upvotes: 0

Views: 10018

Answers (1)

grantnz
grantnz

Reputation: 7423

Your code tests all t1 values at once and is the same as

if all(t1>=0)
    y=1;
else if all(t1<0)
    y=0;

   end

end

What you want is:

t1=-2:0.01:2;
y = zeros(size(t1));
y(t1>=0) = 1;

subplot(3,1,1)
plot(t1,y)

Another (less efficient) way of doing this is:

t1=-2:0.01:2;
for index=1:length(t1)
    if t1(index)>=0
        y(index)=1;
    else if t1(index)<0
            y(index)=0;
        end
    end
end

subplot(3,1,1)
plot(t1,y)

As P0W indicates, there is also the heaviside function which generates step outputs similar to yours (although with the value 0.5 at 0). However, the heaviside function is only available if you have the symbolic toolbox installed.

Upvotes: 4

Related Questions