Call function for all elements in an array

后端 未结 4 1002
鱼传尺愫
鱼传尺愫 2021-01-03 08:20

Let\'s say I have a function, like:

function [result] = Square( x )
    result = x * x;
end

And I have an array like the following,

4条回答
  •  礼貌的吻别
    2021-01-03 08:54

    I am going to assume that you will not be doing something as simple as a square operation and what you are trying to do is not already vectorised in MATLAB.

    It is better to call the function once, and do the loop in the function. As the number of elements increase, you will notice significant increase in operation time.

    Let our functions be:

    function result = getSquare(x)
        result = x*x; % I did not use .* on purpose
    end
    
    function result = getSquareVec(x)
    result = zeros(1,numel(x));
        for idx = 1:numel(x)
            result(:,idx) = x(idx)*x(idx);
        end
    end
    

    And let's call them from a script:

    y = 1:10000;
    tic;
    for idx = 1:numel(y)
        res = getSquare(y(idx));
    end
    toc
    
    tic;
        res = getSquareVec(y);
    toc
    

    I ran the code a couple of times and turns out calling the function only once is at least twice as fast.

    Elapsed time is 0.020524 seconds.
    Elapsed time is 0.008560 seconds.
    
    Elapsed time is 0.019019 seconds.
    Elapsed time is 0.007661 seconds.
    
    Elapsed time is 0.022532 seconds.
    Elapsed time is 0.006731 seconds.
    
    Elapsed time is 0.023051 seconds.
    Elapsed time is 0.005951 seconds.
    

提交回复
热议问题