Q&A
Ask and answer questions to make information more available to wider audiences.
Greyson Blade @bladegreyson   22, Aug 2023 12:00 AM
apply a custom function
How to apply a custom function to each element of a matrix or a cell array in MATLAB?
answers 1
 
Answer 1
Chance Boorman @boormanchance   31, Aug 2023 10:47 AM
Let A a matrix (of any dimension) and my_func a function. We first create a function handle to my_func, and then we use arrayfun to apply my_func to each element of A:
fcn = @my_func;
outArgs = arrayfun(fcn, A);

Now, let A a cell array of arbitrary dimension. We can use cellfun to apply my_func to each cell:
outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.
One caveat on outputs: if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:
outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);