Can someone please give me an example of arrayfun in matlab
Categories:
Mastering arrayfun in MATLAB: Element-wise Operations Made Easy

Explore the power of MATLAB's arrayfun
for applying functions to array elements, enhancing code readability and efficiency.
MATLAB's arrayfun
is a powerful function designed to apply a specified function to each element of an array. It's particularly useful for operations that cannot be easily vectorized directly, or when you want to apply a custom function to each element. While often replaceable by vectorized operations or for
loops, arrayfun
can sometimes offer a more concise and readable solution, especially for complex element-wise transformations.
Understanding the Basics of arrayfun
arrayfun
operates by taking a function handle and one or more arrays as input. It then iterates through the elements of the input arrays, applies the function to corresponding elements, and collects the results into an output array. The output array will have the same size as the input array(s), provided the function returns a single scalar value for each element. If the function returns non-scalar values, arrayfun
can return a cell array.
flowchart TD A[Input Array] --> B{Function Handle} B --> C["Apply Function to Element 1"] B --> D["Apply Function to Element 2"] B --> E["..."] C --> F[Result 1] D --> G[Result 2] E --> H[Result N] F & G & H --> I[Output Array]
Conceptual flow of arrayfun
applying a function to each element of an input array.
%% Example 1: Basic Element-wise Operation
% Define an input array
A = [1, 2, 3, 4, 5];
% Define an anonymous function to square each element
square_func = @(x) x.^2;
% Apply the function using arrayfun
B = arrayfun(square_func, A);
disp('Input Array A:');
disp(A);
disp('Output Array B (squared elements):');
disp(B);
Applying a simple squaring function to each element of an array using arrayfun
.
Handling Multiple Input Arrays and Non-Scalar Outputs
arrayfun
can also handle multiple input arrays, provided they are of the same size. The function handle you provide must then accept multiple arguments. Furthermore, if your function returns non-scalar values (e.g., a vector or a string), you must specify the 'UniformOutput', false
option. This tells arrayfun
to collect the results into a cell array instead of trying to form a uniform numeric array.
%% Example 2: Multiple Input Arrays
% Define two input arrays of the same size
X = [10, 20, 30];
Y = [1, 2, 3];
% Define an anonymous function to add corresponding elements
add_func = @(x, y) x + y;
% Apply the function using arrayfun with two inputs
Z = arrayfun(add_func, X, Y);
disp('Input Array X:');
disp(X);
disp('Input Array Y:');
disp(Y);
disp('Output Array Z (X + Y):');
disp(Z);
%% Example 3: Non-Scalar Output (Cell Array)
% Define an input array of strings
names = {'Alice', 'Bob', 'Charlie'};
% Define a function to append a greeting to each name
greet_func = @(name) ['Hello, ', name, '!'];
% Apply the function, specifying UniformOutput as false
greetings = arrayfun(greet_func, names, 'UniformOutput', false);
disp('Input Names:');
disp(names);
disp('Output Greetings (Cell Array):');
disp(greetings);
Demonstrating arrayfun
with multiple input arrays and with non-scalar outputs requiring 'UniformOutput', false
.
arrayfun
with non-scalar outputs, remember to set 'UniformOutput', false
. Otherwise, MATLAB will throw an error because it won't know how to combine the varying output types into a single matrix.Performance Considerations and Alternatives
While arrayfun
offers conciseness, it's important to understand its performance characteristics. For simple, built-in operations (like +
, *
, sin
, log
), MATLAB's vectorized operations are almost always faster than arrayfun
because they are implemented in highly optimized C code. arrayfun
introduces some overhead due to function call management. For complex custom functions or when dealing with cell arrays, arrayfun
can be a good choice. However, for maximum performance with custom functions on numeric arrays, consider pre-allocating your output and using a traditional for
loop, or exploring parfor
for parallel processing if applicable.
%% Example 4: Vectorized vs. arrayfun vs. For Loop
N = 1e6; % Large number of elements
A = rand(1, N);
% Vectorized operation (fastest)
tic;
B_vec = A.^2;
time_vec = toc;
disp(['Vectorized time: ', num2str(time_vec), ' seconds']);
% arrayfun operation
tic;
B_arr = arrayfun(@(x) x.^2, A);
time_arr = toc;
disp(['arrayfun time: ', num2str(time_arr), ' seconds']);
% For loop operation (often comparable to arrayfun for simple cases, better for complex)
tic;
B_for = zeros(1, N); % Pre-allocation is crucial for for-loops
for i = 1:N
B_for(i) = A(i).^2;
end
time_for = toc;
disp(['For loop time: ', num2str(time_for), ' seconds']);
Comparing performance of vectorized operations, arrayfun
, and a for
loop for a simple squaring operation on a large array.
arrayfun
can be elegant, vectorized operations are generally preferred for speed in MATLAB when applicable. Use arrayfun
when vectorization is not straightforward or for operating on non-numeric data types like cell arrays or structs.