Coding up the step function

  • #1
hunt_mat
Homework Helper
1,741
25
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

Answers and Replies

  • #2
12,483
6,265
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.
 
  • #3
DrClaude
Mentor
7,551
3,893
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).
 
  • Like
Likes jedishrfu and hunt_mat
  • #4
277
97
BTW, an easy MATLAB step function looks like this:


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

Related Threads on Coding up the step function

  • Last Post
Replies
7
Views
5K
  • Last Post
Replies
1
Views
5K
Replies
4
Views
3K
Replies
9
Views
181K
Replies
1
Views
831
Replies
8
Views
13K
Replies
6
Views
33K
Replies
4
Views
4K
  • Last Post
Replies
1
Views
3K
Top