调用数组中所有元素的函数 [英] Call function for all elements in an array

查看:102
本文介绍了调用数组中所有元素的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个如下的数组:

  x = 0:0.1:1; 

我想要一个 y 数组,它使用我的 Square 函数存储 x 的正方形。当然,有一种方法是:

$ p $ y = zeros(1,10);

for i = 1:10
y(i)= Square(x(i));
end

然而,我想应该有一种更优雅的方式。我尝试了一些我的见解并进行了一些搜索,但找不到任何解决方案。任何建议?

解决方案

对于您给出的示例:

  y = x。^ 2; %或
y = x。* x;

其中。* 。^ * ^ 的元素版本。这是最简单,最快捷的方式。



更普遍:

  y = arrayfun(@Square,x ); 

可以很优雅,但与 $相比, b $ b

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

我实际上建议远离 arrayfun ,直到分析表明它比普通循环更快。这将很少,如果有的话。

在新的Matlab版本(R2008及更高版本)中,JIT可以非常有效地加速循环,使得像 arrayfun 在未来的版本中消失。



顺便说一下:请注意,我已经使用 ii 而不是 i 作为循环变量。在Matlab中, i j 是虚构单元的内置名称。如果您将其用作变量名称,则由于必需的名称解析而导致性能下降。使用 i j 以外的任何东西都会阻止这一点。


Let's say I have a function, like:

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

And I have an array like the following,

x = 0:0.1:1;

I want to have an y array, which stores the squares of x's using my Square function. Sure, one way would be the following,

y = zeros(1,10);

for i = 1:10
    y(i) = Square(x(i));
end

However, I guess there should be a more elegant way of doing it. I tried some of my insights and made some search, however couldn't find any solution. Any suggestions?

解决方案

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.

这篇关于调用数组中所有元素的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆