Making ramp and unit step function in MATLAB
151 views (last 30 days)
Robert U on 5 Oct 2017
Edited: Robert U on 5 Oct 2017
Hello Steven Franzkowiak,
one solution is to write a function that behaves as the plotted function. One can argue about the points at t = 4 and t = 8 since they are not defined uniquely. I suppose f(t=4) = 0 and f(t=8) = -2.
The function can look like the following code. Matlab 2017b supports piecewise definition as can be found in one of the links posted by Ramnarayan Krishnamurthy.
function [ vec_out ] = hw_piecewise_R2014b( vec_in )
% support column/row vectors
if size(vec_in,1) > 1
vec_in = vec_in';
transpose_vec = 1;
transpose_vec = 0;
% everywhere else function returns zero
vec_out = zeros(1,size(vec_in,2));
% defined sections of function as seen from chart
vec_out(vec_in >= -6 & vec_in <= 0) = 5/6 * vec_in(vec_in >= -6 & vec_in <= 0) + 5;
vec_out(vec_in > 0 & vec_in <= 4) = -5/4 * vec_in(vec_in > 0 & vec_in <= 4) + 5;
vec_out(vec_in > 4 & vec_in <= 8) = -2;
% return vector according to input
vec_out = vec_out';
Having that function you must define a vector t and call the four versions:
t = -10:0.01:10;
f1 = hw_piecewise_R2014b(t);
f2 = hw_piecewise_R2014b(-t);
f3 = hw_piecewise_R2014b(t-4);
f4 = hw_piecewise_R2014b(2*t - 4)
f5 = hw_piecewise_R2014b(-t/2 - 4)
Sajib Biswas Shuvo on 26 Jul 2021
This code does the job too. It uses the Symbolic Math toolbox.
f_negative_t = 5*heaviside(-t) -5/6 * (-t) * heaviside(-t ) ...
+ 5/6 * (-t-6) * heaviside(-t -6);
f_positive_t = +5*heaviside(t) - 5/4 *t* heaviside(t) ...
- 2*heaviside(t-4) + 5/4*(t-4)*heaviside(t-4)...
f = f_positive_t + f_negative_t;