Mastering MATLAB cellfun for Clean Code

· Admin · 797 words

When working with complex data structures in MATLAB, you will frequently encounter cell arrays. Because cell arrays can hold data of different types and sizes, processing their contents traditionally requires writing explicit for loops. However, looping through cell elements one by one can make your code verbose and slow down execution. This is where MATLAB cellfun comes in as an essential tool for writing concise, vectorized-style code.

【MATLAB】cellfun関数の使い方 | にかわのおぼえがき
Source: nikawa-niwaka.net

By understanding how to leverage cellfun, you can apply a specified function to every cell in an array simultaneously, eliminating boilerplate loops and keeping your scripts clean and performant.

Understanding the Basics of MATLAB cellfun

At its core, cellfun evaluates a function on each cell of a cell array independently. The basic syntax follows a straightforward pattern:

A = cellfun(func, C)

Here, func is a function handle (or a built-in function name as a string), and C is the target cell array. cellfun loops through each element of C, passes it to func, and collects the output into a new array.

Consider a simple example where you want to find the length of several character vectors stored inside a cell array:

C = {'apple', 'banana', 'cherry'};
lengths = cellfun(@length, C);
% Result: lengths = [5, 6, 6]

Instead of initializing an empty vector and writing a loop with length(C{i}), a single line of cellfun handles the iteration internally.

Handling Multiple Inputs and Outputs

cellfun is remarkably flexible and scales beyond single input arrays. You can pass multiple cell arrays simultaneously if your function requires more than one argument.

Processing Multiple Cell Arrays

If you have two cell arrays of the same size, say C1 and C2, you can apply a function that takes two inputs:

C1 = {1, 2, 3};
C2 = {4, 5, 6};
sums = cellfun(@(x, y) x + y, C1, C2);
% Result: sums = [5, 7, 9]

Notice the use of an anonymous function @(x,y) x + y. This allows you to define custom operations on the fly without needing to write a separate function file.

Video: How to Use cellfun with Differently-Sized Input Arrays in Matlab

Extracting Multiple Outputs

cellfun — MATLAB Function Reference | Run Examples Live | RunMat
Source: runmat.com

Sometimes, the function you apply returns more than one output per cell. You can capture all outputs by using multiple output arguments with cellfun, provided you set the UniformOutput parameter appropriately (more on that later).

[minVals, maxVals] = cellfun(@mink, C);

Controlling Output Format: UniformOutput vs. Error Handling

One of the most common stumbling blocks when using cellfun is managing output types. By default, cellfun expects the function applied to every cell to return a scalar of the same data type. It then concatenates these scalars into a standard MATLAB array (matrix or vector).

Uniform Output (true)

When UniformOutput is set to true (the default), MATLAB insists that the output of the function from every cell can be seamlessly concatenated into a non-cell array. If cell 1 returns a scalar and cell 2 returns a vector of length 3, MATLAB will throw an error because the dimensions do not match.

Non-Uniform Output (false)

If your function returns outputs of varying sizes, classes, or dimensions, you must set 'UniformOutput', false. This tells cellfun to wrap the results back into a new cell array:

C = {[1, 2], [3, 4, 5], 6};
% Returns a cell array where each cell contains the original vector plus 10
res = cellfun(@(x) x + 10, C, 'UniformOutput', false);

Performance Considerations: Is cellfun Faster?

A common misconception is that functions like cellfun and arrayfun are inherently faster because they are built-in MATLAB commands. While they are heavily optimized under the hood, they are not always faster than a well-written, pre-allocated for loop.

  • Overhead: cellfun has internal function call overhead. For very small cell arrays, a simple for loop might actually execute faster.
  • JIT Compilation: MATLAB's Just-In-Time (JIT) compiler optimizes standard for loops very effectively in modern versions.
  • Readability: The primary benefit of cellfun is often code cleanliness and declarative style rather than raw speed.

If performance is critical for large datasets, consider whether a cell array is the right structure to begin with. Converting cell data into a standard numeric matrix and using standard vectorized operations will almost always outperform cellfun.

Common Use Cases and Best Practices

To get the most out of cellfun in your everyday MATLAB workflow, keep these scenarios and tips in mind:

  1. Type Checking: Quickly check data types across a mixed cell array using cellfun(@isnumeric, C) or cellfun(@ischar, C).
  2. String Manipulation: Clean up text data stored in cells by applying upper/lower case conversions or regex operations.
  3. Anonymous Functions: Combine cellfun with anonymous functions to perform inline mathematical transformations without cluttering your workspace with helper functions.
  4. Debugging: If a cellfun call fails with an obscure error message, temporarily convert the logic back into a standard for loop to easily inspect which specific cell is causing the failure.

Mastering cellfun bridges the gap between messy cell-iteration loops and clean, professional MATLAB programming.

Image Gallery

MATLAB programming cell arrays optimization vectorization