Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: how to apply function componentwise

Tags:

matlab

Say I have a function calculateStuff(x) that takes in a scalar as parameter and returns a scalar.

Say I have a vector X and I want to apply calculateStuff on every component in X, and get a vector of the results in return and store it in a new vector Y.

Clearly Y=calculateStuff(X) is illegal, is there a way I can do this besides looping?

like image 417
Robert Dennis Avatar asked Feb 13 '11 19:02

Robert Dennis


People also ask

What does Arrayfun mean 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)) .

Can you input an array into a function in MATLAB?

Yes, because all variables are arrays in MATLAB: even scalar values are just 1x1 arrays, so there is absolutely no difference in how they get passed to functions.

What does the function all () do in MATLAB?

B = all( A , 'all' ) tests over all elements of A . This syntax is valid for MATLAB® versions R2018b and later. B = all( A , dim ) tests elements along dimension dim . The dim input is a positive integer scalar.


2 Answers

You have three options:

  1. modify calculateStuff so that it can take arrays and return arrays
  2. write a loop
  3. use arrayfun to hide the loop: Y = arrayfun(@calculateStuff,X)
like image 82
Jonas Avatar answered Oct 01 '22 12:10

Jonas


Most Matlab operations will let you input a matrix and return a matrix. You should be able to re-write calculateStuff() to take a matrix and return a matrix. That is generally MUCH faster than using a for loop. Loops in Matlab are very expensive time-wise.

The sorts of things you need to look at are "dot" versions of normal operations. For example instead of

y = z * x;

do

y = z .* x;

The first will do a matrix multiplication, which is probably not what you want when vectorizing code. The second does an element-by-element multiplication of z and x.

See here and search for "The dot operations".

like image 35
Peter K. Avatar answered Oct 01 '22 13:10

Peter K.