MATLAB Answers

how to use anonymous function with equation without retype the all equation?

16 views (last 30 days)
Dear all,
does anyone know how to use the anonymous function with equation that already defined without type it again. For example,eq1 = x^2+3+y^3; sol=@(x,y) eq1. I tried eq1(2,2) but it does not work as wished. Please help
Best regards, Aziz

  0 Comments

Sign in to comment.

Accepted Answer

Matt J
Matt J on 21 Mar 2017
Edited: Matt J on 21 Mar 2017
If x, y and eq1 are symbolic variables, then there is no reason to be wrapping eq1 in an anonymous function. Just use the subs() command to evaluate eq1 at desired values. E.g.,
>> syms x y
>> eq1 = x^2+3+y^3
eq1 =
x^2 + y^3 + 3
>> val=double(subs(eq1,[x,y],[2,2]))
val =
15
If you insist on wrapping it in anonymous function, you could do something like,
sol=@(a,b) double(subs(eq1,[x,y],[a,b]))

  1 Comment

Walter Roberson
Walter Roberson on 21 Mar 2017
If you are starting from symbolic expressions, then use matlabFunction() to create function handles for numeric processing.

Sign in to comment.

More Answers (2)

Stephen Cobeldick
Stephen Cobeldick on 21 Mar 2017
Edited: Stephen Cobeldick on 21 Mar 2017
>> sol = @(x,y)x^2+3+y^3;
>> sol(2,2)
ans =
15
exactly as the documentation shows:

  3 Comments

Abdulaziz Abutunis
Abdulaziz Abutunis on 21 Mar 2017
Hi Stephen, Thank you for the consideration. I just do not want to retype the equation cause i have iterative process with many solutions(eq1). i want to use it as i mentioned above sol = @(x,y) eq1.
Best
James Tursa
James Tursa on 21 Mar 2017
Then please show us more detail about your problem. Where is the equation coming from? What is this iterative process doing? Etc.
Abdulaziz Abutunis
Abdulaziz Abutunis on 21 Mar 2017
not necessary info for the question..if there is no way to do it then i will switch to another technique

Sign in to comment.


Steven Lord
Steven Lord on 21 Mar 2017
As written, eq1 is not an equation. x and y must be defined before you execute "eq1 = x^2+3+y^3;" or you will receive an error. If you want to define the equation once and use it later, execute:
sol = @(x,y) x.^2+3+y.^3;
Note I used .^ so you can call sol with a nonscalar array, not just a scalar. If you need eq1 to be the value of that function for specific values of x and y:
eq1 = sol(2, 2)

  0 Comments

Sign in to comment.

Sign in to answer this question.