MATLAB: Help plotting a signal pulse

signal processingunit step

I am having trouble creating a signal pulse in matlab. I have to reproduce these images below:
I have u[n] and x[n], but the pulse is "Plot of h[n]" which is just h[n] = u[n] – u[n-3]
I have all my code below, if you scroll towards the bottom where I have a line of code that says:
h = unitstep => 3;
is where I think my problem is.
% Jorge Avila - 1001543128 CSE3313 Signal Processing
%{
Problem Description: This is M.1 on homework 1.
%}
% clears and starts the program without anything on the screen
clc
clear
close all
% (a) create an array from indices -20 to 20
n = -20:20;
% (b) Create a sequence equal to the unit-step function u[n].
unitstep = n >= 0;
% plot u[n] - the unitstep
subplot(2,2,1);
stem(n,unitstep);
xlabel('n indices');
ylabel('u[n]');
title('Plot of u[n]');
% Using what you created in (a) and (b) above, form the following sequence:
% x[n] = ((1/2)^n)(cos((2*pi*n)/13)u[n]
argument = ((2*pi.*n)/13);
x = ((.5).^n).*cos(argument);
% (c) now multiply it by the step function
x = x .* unitstep;
% plotting x[n]
subplot(2,2,2);
stem(n,x);
xlabel('n indices');
ylabel('x[n]');
title('Plot of x[n]');
% (d) Now create sequence h[n]:
% This is basically a PULSE that we have seen already
h = unitstep >= 3;
% plot h[n]
subplot(2,2,3);
stem(n,h);
xlabel('n indices');
ylabel('h[n]');
title('Plot of h[n]');
% (e) convolution
y = conv(x,h,'same');
% plot convolution y[n]
subplot(2,2,4);
stem(n,y);
xlabel('n indices');
ylabel('y[n]');
title('Plot of y[n]');

Best Answer

I always define functions similar to ‘unitstep’ as a function:
unitstep = @(t) t >= 0;
This makes it easier to work with. (The argument itself is not important. I used ‘t’ here because that is generally how the step function is defined.)
Second, since:
I have u[n] and x[n], but the pulse is "Plot of h[n]" which is just h[n] = u[n] - u[n-3]
is now straightforward:
h = unitstep(n) - unitstep(n-3);
and you get the plot you want!
It may be necessary for you to tweak some of the rest of your code to work with the function version of ‘unitstep’. That should not be difficult. (I only ran what was necessary to deal with ‘h’ and plot it, since that appears to be where the problem is.)
Related Question