How to define a piecewise function in matlab?

$\begingroup$

I want to calculate the convolution sum of the continuous unit pulse with itself, but I don't know how I can define this function $$ \delta(t) = \begin{cases} 1, 0 \le t \lt 1 \\ 0, otherwise \end{cases}$$ in Matlab.

$\endgroup$ 1

3 Answers

$\begingroup$

Use the rectangularPulse function.

Or you can define arbitrary piecewise functions in a number of ways, e.g.

ix=x<0

y(ix)=0

ix=x>=1

y(ix)=0

ix=0<=x&x<1

y(ix)=1

$\endgroup$ 2 $\begingroup$

For symbolic math you can take advantage of MuPAD within Matlab. See the documentation for piecewise. You can use this function to concisely produce the example in your question:

pw = evalin(symengine,'piecewise([t >= 0 and t < 1, 1],[Otherwise, 0])')

And you can evaluate it for vector inputs using subs like this:

subs(pw,'t',[1/2 1 0])

which returns

ans =
[ 1, 0, 1]

See the documentation for piecewise for more examples of how to define piecewise functions. There are other ways to call MuPAD functions from Matlab – see here. Of course this method is not meant for performance, so you shouldn't rely on it being as fast as floating-point methods.

$\endgroup$ $\begingroup$

Create a MATLAB function with the following code

function d = delta(t)
if t >= 1 d = 0;
else if t < 0 d = 0;
else d = 1;
end
end

And use delta for whatever reasons you want.

$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like