开发者

Matlab - running a function with parameters for every element of an array?

开发者 https://www.devze.com 2023-03-16 02:50 出处:网络
Matlab has a nice property that scalar functions (such as sin) can work on arrays, operating on any element of the array and returning an array as result.

Matlab has a nice property that scalar functions (such as sin) can work on arrays, operating on any element of the array and returning an array as result.

I have a scalar function f(x,p) where x is a scalar, and p is a parameter (actually an array of parameters). Given a fixed parameter p, I wish to run f(x开发者_StackOverflow中文版,p) on an array A. In a language like Ruby it would look like this:

A.collect{|x| f(x,p)}

But I have no idea how to do it in Matlab for functions that accept parameters and not only the scalar from the array I want to operate on.


The MATLAB equivalent is to supply a function handle taking only a single argument, and sending it to arrayfun.

arrayfun( @(x) f(x, p), A )

For example,

A = 1:10;
p = 2;
arrayfun( @(x) x.^p, A )

Note that the anonymous function creates a closure, capturing the value of p.

0

精彩评论

暂无评论...
验证码 换一张
取 消