Reputation: 1
For some reason when I try to create a simple unit step function I just receive a straight line. I am pretty sure this is correct, but my graph tells me otherwise. Is there something I am doing wrong?
function mone=myOne(t)
[n,~] = size(t);
mone=zeros(n,1);
for i=1:n,
if (t(i)>0),
mone(i) = 1;
end
end
in the command window I type,
t = [-5:0.01:5]
plot(t, myOne(t))
Upvotes: 0
Views: 1033
Reputation: 45752
I can't see anything wrong with the logic behind your function but your implementation is very long winded. In Matlab you can just do this:
function mone=myOne(t)
mone = t > 0;
end
or if you want to get a matrix of numbers and not logicals returned try
function mone=myOne(t)
mone = (t > 0)*1; %// Or if you prefer to cast explicitly:
%// double(t>0)
end
Also to add a shift parameter with default set to zero:
function mone=myOne(t, T)
if nargin < 2
T = 0;
end
mone = (t > T)*1;
end
usage:
t = [-5:0.01:5]
plot(t, myOne(t))
plot(t, myOne(t,3))
Upvotes: 2
Reputation: 2334
The error is your line:
[n,~] = size(t);
You only query the first dimension of t
, which is 1
following
t = [-5:0.01:5]
size(t)
ans =
1 1001
You can either transpose t
t = [-5:0.01:5].';
size(t)
ans =
1001 1
or you length
instead of size
.
n = length(t);
Finally, a solution without the loop as proposed by @Dan is much faster.
Upvotes: 2