Problem with function handle array evaluation

조회 수: 7 (최근 30일)
Matthew
Matthew 2022년 9월 28일
댓글: Matthew 2022년 9월 28일
I have created the function handle:
f1 = @(x) [5*x , 3*x , 1];
I want to evaluate the function over a column vector of variable length. i.e:
dx = .5; % dx can be any number less than 1
%f1([0:dx:1]')
But I get the issue where it fails to concatentate the array.
This issue does not occur when all components of the function array are functions. i.e:
f2 = @(x) [5*x , 3*x , x];
f2([0:dx:1]')
ans = 3×3
0 0 0 2.5000 1.5000 0.5000 5.0000 3.0000 1.0000
I believe the issue stems from how matlab evaluates the function. As in it evaluates each individual component of the array into its own column vector and then concatenates them. But since the third coponent of f1 is a scalar, it does not create a column vector of 1's with length of the input. And when it concatenates, the vectors are of different size and it fails.
How do I get f1 to evaluate into a matrix like f2 did?
Sadly I can't do this:
f1 = @(x) [5*x , 3*x , 1+0*x];
because I don't actually control f1, its an unknown symbolic array equation that is converted into a function handle through matlabFunction().
I also can't use a for loop to individually evaluate each parameter in the input column vector because dx gets very small and a for loop would significantly increase processing time.
Any help would be appreciated

채택된 답변

Steven Lord
Steven Lord 2022년 9월 28일
Define two helper functions:
apply = @(fun, x) arrayfun(fun, x, 'UniformOutput', false);
stack = @(x) vertcat(x{:});
Now let's define your function:
f = @(x) [5*x, 3*x, 1];
Call it:
x = [1 2 3];
y = stack(apply(f, x))
y = 3×3
5 3 1 10 6 1 15 9 1
y is created by stacking the vectors created by applying f to the elements of x.
  댓글 수: 1
Matthew
Matthew 2022년 9월 28일
That works, thank you very much for your help

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by