How to extract an element from a ''vector'' of function handle
Show older comments
Hi guys,
I'm having some troubles managing handle functions.
What I would like to do is to extract an element of an "handle" array like this below.
f = @(x1,x2,x3)[x1*2-x3;x3*x1-x2;x1-x2^2]
And I would like to compute "something" like that.
f(1) = x1*2-x3;
f(2) = x3*x1-x2;
f(3) = x1-x2^2;
So, like a vector.
How can I do that ??
Accepted Answer
More Answers (1)
It seems like you want a cell array of function handles:
f = {@(x1,x2,x3)x1*2-x3; @(x1,x2,x3)x3*x1-x2; @(x1,x2,x3)x1-x2^2}
f{1}
f{2}
f{3}
Then you can evaluate the functions one at a time:
f{1}(10,13,15)
f{2}(10,13,15)
f{3}(10,13,15)
Or all at once:
cellfun(@(x)x(10,13,15),f)
3 Comments
Fangjun Jiang
on 1 Apr 2022
This is from "doc function_handle"
With one exception, function handles can be manipulated and operated on in
the same manner as other MATLAB values, including assignment to variables
and inclusion in cells and structs. The exception is that you cannot
construct a function_handle array. The reason is that the parenthesis
notation for values of this class is used to call a function, not to
index an array. To achieve the effect of an array of function handles,
use cells, e.g., write "A = {@sin, @cos}" rather than "A = [@sin, @cos]".
Of course, you need to index A with braces: "A{i}".
Luca Amicucci
on 1 Apr 2022
I see. Then maybe something like this would work, depending on what f1, f2 and f3 actually are:
% a function handle you have
results = @(x1,x2,x3) [f1;f2;f3]
% make it a char vector:
str = func2str(results)
% parse the char vector into argument list and functions f1, f2, f3:
f = regexp(str,'(@\(.+\))\[(.+);(.+);(.+)\]','tokens');
f = [f{:}]
% make a cell array of function handles out of that argument list and each
% function (f1, f2, f3):
f = cellfun(@(x)str2func([f{1} x]),f(2:end),'UniformOutput',false)
Now you have a cell array of function handles to those individual functions.
Categories
Find more on Operators and Elementary Operations 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!