Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

matlab

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.

like image 329
Gadi A Avatar asked Jun 27 '11 12:06

Gadi A


People also ask

How do you apply a function to each element of a matrix in MATLAB?

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

What does the function all () do in MATLAB?

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.

Is Arrayfun faster than for loop?

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.


1 Answers

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.

like image 174
Edric Avatar answered Oct 05 '22 23:10

Edric