Creating a row vector of function handles

15 views (last 30 days)
Saurabh Madankar
Saurabh Madankar on 18 Feb 2022
Answered: Simar on 16 Oct 2023
I have pre-defined function handles f_{i} using cell arrays for say i =1 to 8, so total 8 function handles. Now how do I create a new function handle, say g, which is a row vector consisting of these 8 function handles?
  1 Comment
Stephen23
Stephen23 on 18 Feb 2022
Edited: Stephen23 on 18 Feb 2022
Function handles are the only fundamental data type that cannot be concatenated into arrays. They are scalar only:
Multiple function handles can be stored in container class arrays, e.g. structure arrays, cell arrays.

Sign in to comment.

Answers (1)

Simar
Simar on 16 Oct 2023
Hi Saurabh,
I understand that you want to create a new function handle, which should be a row vector consisting of pre-defined function handles.To define a new function handle ‘g’ as a cell array of function handles ‘f_{i}, here is a simple way to do this:
% Assuming f_{i} are pre-defined
f{1} = @(x) x^2; % Example function handle
f{2} = @(x) x^3; % Example function handle
f{3} = @(x) x^4; % Example function handle
f{4} = @(x) x^5; % Example function handle
f{5} = @(x) x^6; % Example function handle
f{6} = @(x) x^7; % Example function handle
f{7} = @(x) x^8; % Example function handle
f{8} = @(x) x^9; % Example function handle
% Create new function handle g
g = @(x) cellfun(@(f) f(x), f, 'UniformOutput', false);
Here, g represents an anonymous function. This function takes one input ‘x’ and applies it to each function handle in the cell array ‘f’. The ‘cellfun’ function applies a function to each cell in a cell array. The function being applied is ‘@(f) f(x)’, which takes a function handle ‘f’ and applies it to x.
The 'UniformOutput', false argument is necessary because the functions in f might not all return outputs of the same type or size. If all functions in f are guaranteed to return scalars, you can omit this argument to get a numeric array output instead of a cell array. You can call g with a scalar input like this:
results = g(2); % Apply all functions in f to the number 2
results will be a 1-by-8 cell array where each element is the output of one of the functions in ‘f’ applied to 2.
results =
[4] [8] [16] [32] [64] [128] [256] [512]
To return a row vector instead of a cell array, modify the definition of g. In this case, g(2) will be a 1-by-8 numeric array.
g = @(x) cell2mat(cellfun(@(f) f(x), f, 'UniformOutput', false));
results = g(2)
results =
[4, 8 , 16, 32, 64, 128, 256, 512]
Kindly refer to the documentation links below for further information:
Hope it helps!
Best Regards
Simar

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!