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,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.
B = arrayfun( func , A ) applies the function func to the elements of A , one element at a time. arrayfun then concatenates the outputs from func into the output array B , so that for the i th element of A , B(i) = func(A(i)) .
The all function reduces such a vector of logical values to a single condition. In this case, B = all(A < 0.5) yields logical 0 . This makes all particularly useful in if statements. The code is executed depending on a single condition, rather than a vector of possibly conflicting conditions.
For example, I tested arrayfun vs a forloop, squaring the elements, and the speed difference was a factor of two. While this is concrete evidence that we should always use for loops instead of arrayfun, it's obvious that the benefit varies.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With