Combining function handles into one function handle

조회 수: 14 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by