comparison of loop and vectorization in matlab

后端 未结 4 679
轮回少年
轮回少年 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:13

    In the first case you are comparing an array to the value 0. This will give the result [0 0 1 0 0], which is not a simple true or false. So the statement y = 0; will not get executed and f will be [0 0 0 0 0] as shown.

    In the second you are iterating through the array value by value and passing it to the function. Since the array contains the value 0, then you will get 1 back from the function in the print out of f (or [0 0 1 0 0], which is an impulse).

    You'll need to modify your function to take array inputs.

    Perhaps this example will clarify the issue further:

    cond = 0;
    if cond == 0
        disp(cond) % This will print 0 since 0 == 0
    end
    
    cond = 1;
    if cond == 0
        disp(cond) % This won't print since since 1 ~= 0 (not equal)
    end
    
    cond = [-2 -1 0 1 2];
    if cond == 0
        disp(cond) % This won't print since since [-2 -1 0 1 2] ~= 0 (not equal)
    end
    
    0 讨论(0)
  • 2021-01-24 05:15

    Your function is not defined to handle vector input.

    Modify your impluse function as follows:

    function y=impulse_function(n)
        [a b]=size(n);
        y=zeros(a,b);
        y(n==0)=1;
    end
    

    In your definition of impulse_function, whole array is compared to zero and return value is only a single number instead of a vector.

    0 讨论(0)
  • 2021-01-24 05:27

    You can write an even simpler function:

    function y=impulse_function(n);
    y = n==0;
    

    Note that this will return y as a type logical array but that should not affect later numerical computations.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题