How to extract an element from a ''vector'' of function handle
28 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Luca Amicucci
am 1 Apr. 2022
Kommentiert: Steven Lord
am 2 Apr. 2022
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 ??
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 1 Apr. 2022
If you've already created your f function you could do this using one helper function. I vectorized your f function.
f = @(x1,x2,x3)[x1*2-x3;x3.*x1-x2;x1-x2.^2];
getRow = @(data, rowNum) data(rowNum, :); % Helper function
Now if you want a function handle that retrieves the third row in the output of f:
g3 = @(x1, x2, x3) getRow(f(x1, x2, x3), 3);
Check the full output versus the row 3 output:
y123 = f(1:5, 6:10, 11:15)
y3 = g3(1:5, 6:10, 11:15)
You could theoretically eliminate the getRow function by explicitly calling subsref yourself inside g3, but using a separate getRow function makes the code much clearer IMO.
5 Kommentare
Steven Lord
am 2 Apr. 2022
Years ago MATLAB did allow you to have a vector of function handles, but that functionality was removed when we introduced anonymous functions (to avoid ambiguity: would f(3) be a call to the function with the input 3 or a request for the third element of the array?) If you want an array of function handles it must be a cell array.
Q = {@sin, @cos, @tan};
Now Q{2} is unambiguous and so is Q{2}(pi).
f = Q{2}(pi)
Weitere Antworten (1)
Voss
am 1 Apr. 2022
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 Kommentare
Voss
am 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.
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!