comparison of loop and vectorization in matlab

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

提交回复
热议问题