comparison of loop and vectorization in matlab

后端 未结 4 677
轮回少年
轮回少年 2021-01-24 04:46

let us consider following code for impulse function

function y=impulse_function(n);
y=0;
if n==0
    y=1;
end
end

this code

>         


        
4条回答
  •  别那么骄傲
    2021-01-24 05:30

    You could define your impulse function simply as this one -

    impulse_function = @(n) (1:numel(n)).*n==0
    

    Sample run -

    >> n = -6:4
    n =
        -6    -5    -4    -3    -2    -1     0     1     2     3     4
    >> out = impulse_function(n)
    out =
         0     0     0     0     0     0     1     0     0     0     0
    

    Plot code -

    plot(n,out,'o')    %// data points
    hold on
    line([0 0],[1 0])  %// impulse point
    

    Plot result -

    enter image description here

提交回复
热议问题