Combining function handles into one function handle

19 ビュー (過去 30 日間)
Kfir Assor
Kfir Assor 2020 年 8 月 4 日
編集済み: Fangjun Jiang 2020 年 8 月 4 日
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
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
Kfir Assor 2020 年 8 月 4 日
Let's say I have a loop, where in each iteration I create one more function handle. I want to create a SIMO function handle that looks like that: d=@(x) [a1(x);a2(x);a3(x),...,a(n)].
Fangjun, I'm not interested in the solution of x=1:4, I need the function handle itself. If I could do [f{1};f{2}] that would be great but I can't vertcat nonscalar arrays of function handles.
Fangjun Jiang
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
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)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by