Matlab - running a function with parameters for every element of an array?
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
.
精彩评论