how to make an anonymous function with more than 1 statement or equation?

11 ビュー (過去 30 日間)
Alfandias Saurena
Alfandias Saurena 2022 年 2 月 17 日
回答済み: Walter Roberson 2022 年 2 月 17 日
for exmple, i have 2 or more equation (a and d), with some variable defined (B and C).
B=2
C=4
a=Bx;
d=Cx^2;
then, i want to solve :
sqrt(a+d)
B=2;
C=4;
f=@(x) (a=B*x) (d=C*x^2) sqrt(a+b);
Unsupported use of the '=' operator. To compare values for equality, use '=='. To specify name-value arguments, check that name is a valid identifier with no surrounding quotes.
f(2)

採用された回答

Stephen23
Stephen23 2022 年 2 月 17 日
Using anonymous functions:
B=2;
C=4;
Fa = @(x) B.*x;
Fd = @(x) C.*x.^2;
Fh = @(x) sqrt(Fa(x)+Fd(x));
Fh(2)
ans = 4.4721
Using the symbolic toolbox:
syms x
a = B*x;
d = C*x^2;
s = sqrt(a+d)
s = 
double(subs(s,2))
ans = 4.4721

その他の回答 (2 件)

Arif Hoq
Arif Hoq 2022 年 2 月 17 日
編集済み: Arif Hoq 2022 年 2 月 17 日
B=2;
C=4;
f=@(x) B*x +C*x^2;
% d=@(x) C*x^2
sqrt(f(2))
ans = 4.4721

Walter Roberson
Walter Roberson 2022 年 2 月 17 日
To answer your original question as phrased:
I suspect that you could do that with careful use of having the anonymous function invoke evalc() with a character vector that was a command line that used evalin('caller') to retrieve the parameter, and assingin('base') to save the variable, and then a series of assignin('base') and evalin('base') calls.
This would not be recommended even a little, but you did not ask for our recommendations, only for how to do that task using multiple statements inside an anonymous function.
The approaches shown by Stephen are much better. I would have to have a really good reason to use the approach I outlined above, at least for anything other than proving it could be done.

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by