Creating a row vector of function handles

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

Stephen23
Stephen23 2022년 2월 18일
편집: Stephen23 2022년 2월 18일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Simar
Simar 2023년 10월 16일

1 개 추천

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

카테고리

도움말 센터File Exchange에서 Data Type Identification에 대해 자세히 알아보기

질문:

2022년 2월 18일

답변:

2023년 10월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by