Calling a automatically generated vector valued function handle with a vector

Hello everyone,
I am frequently running into the following problem when I generate a function handle from a symbolic expression like in the following simplified example:
syms x
f = [x,0]
fh = matlabFunction(f) % this is equivalent to fh = @(x) [x,0.0]
X = [1;2;3]
fh(X)
The code above produces the obvious error:
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in symengine>@(x)[x,0.0]
Until now I used the 'File' option of matlabFunction and changed the definiton of the function inside the generated file to
fh = @(x) [x,0*x]
but this requires user intervention, which I want to avoid.
Can anybody think of a general solution wich dous not require user intervention and also works for an arbitrary number of collums returend by the function handle?
Thank you!

3 件のコメント

Matt J
Matt J 2022 年 3 月 23 日
when I generate a function handle from a symbolic expression like in the following simple example:
There don't appear to be any symbolic expressions in this example.
Michael Gfrerer
Michael Gfrerer 2022 年 3 月 23 日
Sorry for being unclear. Now, I changed the question and provided the right context.
But the only reason the function definition works in the symbolic domain is because x is a scalar. If this weren't the case, you would have the same problem, e.g.,
syms x [3,1]
f = [x,0]
Error using sym/cat>checkDimensions
CAT arguments dimensions not consistent.

Error in sym/cat>catMany (line 33)
[resz, ranges] = checkDimensions(sz,dim);

Error in sym/cat (line 25)
ySym = catMany(dim, args);

Error in sym/horzcat (line 19)
ySym = cat(2,args{:});

サインインしてコメントする。

回答 (2 件)

Matt J
Matt J 2022 年 3 月 23 日
編集済み: Matt J 2022 年 3 月 23 日
Because the original symbolic function is defined only on R^1, you must post-vectorize the matlabFunction output.
syms x
f = [x,0]; %scalar form
fh = matlabFunction(f);
fh=@(x) cell2mat( arrayfun(fh,x,'uni',0)); %add vectorization
fh([1;2;3])
ans = 3×2
1 0 2 0 3 0

2 件のコメント

Michael Gfrerer
Michael Gfrerer 2022 年 3 月 24 日
Thank you for your answer!
Are you able to generalize this for an arbitray number of symbolic variables?
Matt J
Matt J 2022 年 3 月 24 日
Can you give an example?

サインインしてコメントする。

Walter Roberson
Walter Roberson 2022 年 3 月 23 日

0 投票

No, there is no method at the moment other than hand manipulation.
I created a service request about related issues a couple of months ago. I suggest you also create a service request, as they prioritize in part according to how much user request there has been.

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

製品

リリース

R2021b

質問済み:

2022 年 3 月 23 日

コメント済み:

2022 年 3 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by