Skip to content

MATLAB - Map Function

MATLAB - Applying Functions to Array Elements

Section titled “MATLAB - Applying Functions to Array Elements”

A common programming task is to apply a specific operation or function to every element in an array. While many languages use a map function for this, MATLAB encourages a more efficient and readable approach called vectorization. For cases where vectorization isn’t possible, MATLAB provides the arrayfun and cellfun functions.

Vectorization is the process of rewriting loop-based, scalar-oriented code to use MATLAB’s matrix and vector operations. It is faster and more idiomatic because MATLAB is highly optimized for array operations. You should always try to use vectorization first.

Let’s say you have an array of numbers and want to square each one.

% The slow, loop-based way (avoid this if possible)
input_array = [1, 2, 3, 4, 5];
output_array = zeros(size(input_array)); % Pre-allocate for performance
for i = 1:length(input_array)
output_array(i) = input_array(i)^2;
end
% The fast, vectorized way (BEST way)
input_array = [1, 2, 3, 4, 5];
output_array_vectorized = input_array.^2; % The .^ operator is element-wise power
disp(output_array_vectorized);

The vectorized version is cleaner, more concise, and significantly faster, especially for large arrays. The output is:

1 4 9 16 25

Using arrayfun for Numeric Arrays (When Necessary)

Section titled “Using arrayfun for Numeric Arrays (When Necessary)”

You should use arrayfun when the function you want to apply cannot be easily vectorized. arrayfun applies a function to each element of an array, but it is often just a cleaner syntax for a for loop and does not provide the same performance benefit as true vectorization.

B = arrayfun(func, A)
  • B: The output array.
  • func: A handle to the function you want to apply. This is often an anonymous function created with @.
  • A: The input array.

Example: Applying a Custom, Non-Vectorized Function

Section titled “Example: Applying a Custom, Non-Vectorized Function”

Imagine you have a complex custom function that only operates on scalar inputs.

% Let's define a custom function that is not vectorized
my_complex_func = @(x) sin(x) + x^2 - log(x);
% Array of numbers
input_array = [1, 2, 3, 4, 5];
% Use arrayfun to apply the function to each element
output_array = arrayfun(my_complex_func, input_array);
disp(output_array);

While this works, a better long-term solution would be to rewrite my_complex_func to be vectorized:

% Vectorized version of the function
my_vectorized_func = @(x) sin(x) + x.^2 - log(x);
output_better = my_vectorized_func(input_array); % This is faster!

Cell arrays can contain different types and sizes of data in each cell, so vectorization is not possible. For these, cellfun is the appropriate tool.

B = cellfun(func, C)

In modern MATLAB, you should use string arrays for text. But if you have a legacy cell array of character vectors, cellfun is perfect.

% Create a cell array of character vectors
input_cell_array = {'apple', 'banana', 'cherry'};
% Use cellfun to apply the length function to each element
% Note: In modern MATLAB, strlength() on a string array is preferred
lengths = cellfun(@length, input_cell_array);
disp(lengths);

The result is an array of the lengths:

5 6 6

Example 2: Sum Each Numeric Array in a Cell

Section titled “Example 2: Sum Each Numeric Array in a Cell”

If each cell contains a numeric array of a different size, cellfun can process them.

% Create a cell array of numeric arrays
numeric_cells = {[1, 2, 3], [4, 5], [6, 7, 8, 9]};
% Define a function handle to compute the sum
sum_function = @(arr) sum(arr);
% Use cellfun to apply the sum function
output_sums = cellfun(sum_function, numeric_cells);
disp(output_sums);

The result is the sum of each cell’s contents:

6 9 30
  1. Vectorize First: Always try to use element-wise operators (.*, ./, .^) and vectorized functions (sin, log, sum, etc.) for the best performance and readability.
  2. Use arrayfun Sparingly: Reserve arrayfun for numeric arrays only when a function cannot be vectorized.
  3. Use cellfun for Cell Arrays: This is the intended and efficient way to process the heterogeneous contents of cell arrays.
  4. 'UniformOutput', false: If the function you apply with cellfun or arrayfun returns values of different types or sizes, you must specify this name-value pair. The result will be a cell array. Example: sizes = cellfun(@size, numeric_cells, 'UniformOutput', false);