Combining function handles into one function handle
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Is there a convenient way where I can combine N SISO function handles to create one SIMO function handle?
For example of N=2, if I got:
a = @(x) x(1)^2+x(2)^2;
b = @(x) x(3)^2-x(4)^2;
I would like to create a single function handle like:
c = @(x) [x(1)^2+x(2)^2; x(3)^2-x(4)^2];
Thanks in advance!
0 Kommentare
Antworten (2)
Fangjun Jiang
am 4 Aug. 2020
>> a = @(x) x(1)^2+x(2)^2;
b = @(x) x(3)^2-x(4)^2;
>> a(1:4)
ans =
5
>> b(1:4)
ans =
-7
>> c = @(x) [x(1)^2+x(2)^2; x(3)^2-x(4)^2];
>> c(1:4)
ans =
5
-7
>> d=@(x) [a(x);b(x)]
d =
function_handle with value:
@(x)[a(x);b(x)]
>> d(1:4)
ans =
5
-7
>>
5 Kommentare
Fangjun Jiang
am 4 Aug. 2020
Bearbeitet: Fangjun Jiang
am 4 Aug. 2020
treat the function handles the same as strings, as in cellstr(). You can't put function handles in a regular array, but you can put them in a cell array.
suppose you have function handles defined in f{1}, f{2}, f{3}, ..., f{n}
then at any iteration k, your SIMO function handle is d=f(1:k). Again, it is a cell array of function handles. If you want to use this function handle cell array d to evaluate without for-loop, Bruno Luong has provided answer below. I can just use a simple example:
%%
f{1}=@(x) x(1)^2+x(2)^2;
f{2}=@(x) x(3)^2-x(4)^2;
f{3}=@(x) x(1)*x(4);
y=1:4;
for k=1:numel(f)
d=f(1:k);
out=@(x) cellfun(@(f) f(x), d);
result=out(y)
end
result =
5
result =
5 -7
result =
5 -7 4
Bruno Luong
am 4 Aug. 2020
Bearbeitet: Bruno Luong
am 4 Aug. 2020
a = @(x) x(1)^2+x(2)^2;
b = @(x) x(3)^2-x(4)^2;
c = @(x) x(1)*x(4);
% suppose your for-loop puts each function handle in a cell array like this
allfun = {a, b, c};
vecfun = @(x) cellfun(@(f) f(x), allfun(:));
x = rand(1,4);
a(x)
b(x)
c(x)
vecfun(x)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!