How can you use symbolic functions as inputs and outputs of regular matlab functions
Show older comments
I want to use a symbolic expression as an input to a regular old matlab function and I want the matlab function to return a different symbolic function. For example, I want to be able to go:
syms x;
f(x)=sin(x);
new_function=function_I_will_write(f);
And then new_function(x) will output the symbolic variable x or something.
1 Comment
Matt Grant
on 25 Sep 2017
Answers (2)
Walter Roberson
on 22 Sep 2017
In cases where function_I_will_write never compares the input to anything (e.g., tests for negative), and does not specifically test for numeric data types, it is common for passing symbolic expressions to "just work". There are cases where there are conflicts between numeric routines and symbolic routines. For example, if you have
syms x;
f(x)=sin(x);
X = sym('X', [1 10]);
result = my_routine( f(X) )
then you would have problems if my_routine is, for example,
function M = my_routine( v )
M = max( diff(v) );
because diff() of symbolic values is differentiation whereas the routine is expecting to do numeric differences equivalent to v(2:end) - v(1:end-1) for vectors.
1 Comment
Matt Grant
on 25 Sep 2017
Ethan Duckworth
on 28 Apr 2022
If I understand what you want to do, I think it can be done by querying the input to get the variable, then using whatever syms variable inside the function you want via subs, and then changing back for the output.
Here's an example:
function out = add_x(f)
syms y;
fvar = symvar(f);
f=subs(f,fvar,y);
out= y + f;
out = subs(out,y,fvar);
end
when I run this I get the following
syms t
f(t)=t^2
g = add_x(f) % ha ha, it's not x that's added
g(t)=t^2+t
Categories
Find more on Code Performance in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!