调用数组中所有元素的函数

编程入门 行业动态 更新时间:2024-10-20 00:45:36
本文介绍了调用数组中所有元素的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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 );

可以很优雅,但与 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.

更多推荐

调用数组中所有元素的函数

本文发布于:2023-10-24 19:58:38,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!