Call function for all elements in an array

后端 未结 4 1004
鱼传尺愫
鱼传尺愫 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 09:02

    For the example you give:

    y = x.^2;   % or
    y = x.*x;
    

    in which .* and .^ are the element-wise versions of * and ^. This is the simplest, fastest way there is.

    More general:

    y = arrayfun(@Square, x);
    

    which can be elegant, but it's usually pretty slow compared to

    y = zeros(size(x));
    for ii = 1:numel(x)
        y(ii) = Square(x(ii)); end
    

    I'd actually advise to stay away from arrayfun until profiling has showed that it is faster than a plain loop. Which will be seldom, if ever.

    In new Matlab versions (R2008 and up), the JIT accelerates loops so effectively that things like arrayfun might actually disappear in a future release.

    As an aside: note that I've used ii instead of i as the loop variable. In Matlab, i and j are built-in names for the imaginary unit. If you use it as a variable name, you'll lose some performance due to the necessary name resolution required. Using anything other than i or j will prevent that.

提交回复
热议问题