Anonymous Functions with Multiple Inputs ignore some inputs

For example, the function is: , then
But I want to do this: or , and so on
y=@(x,theta) x.^theta
y(2,3)=8 % 2^3=8, succeed
% But I want is :
y(2, theta) % My ideal output is: 2.^theta but it doesn't work
y(x, 2) % I need is: x.^2
hope I made it clear enough....

3 件のコメント

Bjorn Gustavsson
Bjorn Gustavsson 2022 年 6 月 6 日
@ defines a numerical function, that is a "normal" numerical function that is typically used to return numerical values. In your case it would work perfectly fine to do
theta = [0.5 1 3 2]
x = 2
y(x,theta)
If you want the litteral 2.^theta you should look at what the symbolic toolbox gives you.
Walter Roberson
Walter Roberson 2022 年 6 月 6 日
Symbolic is good for this purpose.
In the special case where you do not capture any variables in the anonymous function handle, you could use formula() on the handle, and do text processing to replace all references to the parameter with the numeric constant, and strip the name out of the @() section, and then use str2func. Symbolic toolbox is much more convenient though... especially if you need to get right the possibility that the anonymous function has an anonymous function with the same parameter name
@(x,y) y.^integral(@(x)x.^2, 0,x)
The @(x)x.^2 should not be replaced when x is being replaced with something constant in the anonymous function...
Jun Liang
Jun Liang 2022 年 6 月 18 日
Thanks, I have used symbolic toolbox to solve this problem.
code:
syms phi(x, theta)
phi(x, theta) = x.^theta;
% phi(2,theta) or phi(x,2) are working

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

回答 (0 件)

カテゴリ

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

質問済み:

2022 年 6 月 6 日

コメント済み:

2022 年 6 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by