Combining function handles into one function handle
古いコメントを表示
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!
回答 (2 件)
Fangjun Jiang
2020 年 8 月 4 日
>> 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 件のコメント
Kfir Assor
2020 年 8 月 4 日
Steven Lord
2020 年 8 月 4 日
How do you have your many function handles stored? You don't have them stored in numbered variables, do you?
Depending on how they're stored (cell array?) and what they return (scalars or non-scalars, outputs of the same size and type, outputs of different sizes and/or types, etc.) using cellfun may be of use.
Fangjun Jiang
2020 年 8 月 4 日
In that case, no need to create separate function handles and then combine them, use cell array of function handles, and you can use for-loop easily
f{1}=@(x) x(1)^2+x(2)^2;
f{2}=@(x) x(3)^2-x(4)^2;
f{1}(1:4)
[f{1}(1:4);f{2}(1:4)]
Kfir Assor
2020 年 8 月 4 日
Fangjun Jiang
2020 年 8 月 4 日
編集済み: Fangjun Jiang
2020 年 8 月 4 日
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
2020 年 8 月 4 日
編集済み: Bruno Luong
2020 年 8 月 4 日
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)
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!