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.
The Best Practice: Vectorization
Section titled “The Best Practice: Vectorization”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.
Example: Squaring Each Element
Section titled “Example: Squaring Each Element”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 performancefor 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 25Using 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.
Syntax
Section titled “Syntax”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 vectorizedmy_complex_func = @(x) sin(x) + x^2 - log(x);
% Array of numbersinput_array = [1, 2, 3, 4, 5];
% Use arrayfun to apply the function to each elementoutput_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 functionmy_vectorized_func = @(x) sin(x) + x.^2 - log(x);output_better = my_vectorized_func(input_array); % This is faster!Using cellfun for Cell Arrays
Section titled “Using cellfun for Cell Arrays”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.
Syntax
Section titled “Syntax”B = cellfun(func, C)Example 1: Get the Length of Each String
Section titled “Example 1: Get the Length of Each String”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 vectorsinput_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 preferredlengths = cellfun(@length, input_cell_array);
disp(lengths);The result is an array of the lengths:
5 6 6Example 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 arraysnumeric_cells = {[1, 2, 3], [4, 5], [6, 7, 8, 9]};
% Define a function handle to compute the sumsum_function = @(arr) sum(arr);
% Use cellfun to apply the sum functionoutput_sums = cellfun(sum_function, numeric_cells);
disp(output_sums);The result is the sum of each cell’s contents:
6 9 30Performance & Best Practices Summary
Section titled “Performance & Best Practices Summary”- Vectorize First: Always try to use element-wise operators (
.*,./,.^) and vectorized functions (sin,log,sum, etc.) for the best performance and readability. - Use
arrayfunSparingly: Reservearrayfunfor numeric arrays only when a function cannot be vectorized. - Use
cellfunfor Cell Arrays: This is the intended and efficient way to process the heterogeneous contents of cell arrays. 'UniformOutput', false: If the function you apply withcellfunorarrayfunreturns 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);