# Coding up the step function

• MATLAB
Homework Helper
I wrote some code that is supposed to give me the step function:
Matlab:
function y=step_fn(x,a,b)
%This is the step function, given a range from a to b, it wil produce a
%function which is 1 from a to b and zero otherwise.
L=length(x);
y=zeros(1,L);
n=find(x<=a,1,'last');
if (b==max(x))
m=L;
else
m=find(x>=b,1,'first');
end
if (n==1)
y(n:m-1)=1;
else
y(n+1:m)=1;
end

This all looks good, however when I do the following:
Matlab:
x=linspace(0,5,500);
D=1.5*step_fn(x,0,2)+2*step_fn(x,2,4)+0.5*step_fn(x,4,5);

I get the attached plot. I don't quite understand . Does anyone understand where I am going wrong?
I get similar odd results with the smooth approximation using the erf function.

#### Attachments

• step.jpg
13.6 KB · Views: 402

jedishrfu
Mentor
Why not use Matlab to debug it by looking at the output of each line of code?

This way you can localize your error to perhaps a single line or more and research that line.

DrClaude
Mentor
You are checking the boundaries using <= and >=, meaning that both extremities get included. In other words step_fn(x,2,4) returns 1 for x=4, and step_fn(x,4,5) also returns 1 for x=4, so the two get added up. The only reason it doesn't happen at x=2 is that , for some reason, you decided to exclude the last point if the interval starts at the first point in x, so step_fn(x,0,2) returns 0 for x=2.

You need to decide which of step_fn(x,a,b) or step_fn(x,b,c) equals 1 when x is exactly b (or set step_fn(x,a,b) to return 0.5 when x is exactly a or b).

jedishrfu and hunt_mat
BTW, an easy MATLAB step function looks like this:

step_fn = @(x,a,b) x>=a & x<=b;