简体   繁体   English

MATLAB:单位步长函数

[英]MATLAB: Unit step function

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))

The error is your line: 错误是您的行:

[n,~] = size(t);

You only query the first dimension of t , which is 1 following 您仅查询t的第一个维度,即1以下

t = [-5:0.01:5]
size(t)

ans =

       1        1001

You can either transpose t 您可以移调t

t = [-5:0.01:5].';
size(t)

ans =

        1001           1

or you length instead of size . 或者您用length而不是size

n = length(t);

Finally, a solution without the loop as proposed by @Dan is much faster. 最后,@ Dan提出的没有循环的解决方案要快得多。

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: 在Matlab中,您可以执行以下操作:

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: 还要添加一个默认设置为零的shift参数:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM