comparison of loop and vectorization in matlab

℡╲_俬逩灬. 提交于 2020-01-22 00:20:41

问题


let us consider following code for impulse function

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

this code

>> n=-2:2;
>> i=1:length(n);
>> f(i)=impulse_function(n(i));
>> 

returns result

 f

f =

     0     0     0     0     0

while this code

>> n=-2:2;
>> for i=1:length(n);
f(i)=impulse_function(n(i));
end
>> f

f =

     0     0     1     0     0

in both case i is 1 2 3 4 5,what is different?


回答1:


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.




回答2:


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



回答3:


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 -




回答4:


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.



来源:https://stackoverflow.com/questions/28937295/comparison-of-loop-and-vectorization-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!