Problem with function handle array evaluation

6 ビュー (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by