5

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.

1

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.