Find constants in a symbolic vector

2 views (last 30 days)
Hello friends!
I have a simple question but found it difficult to come up with a perfect answer. I explain by a simple example. Consider the following
syms x y
f = [x^2+y; 2; 3*x^4*y^2; 5; 1/x; 12];
What I need to get is the vector [x^2+y; 3*x^4*y^2; 1/x]. However, this trurns out to be difficult to implement. One idea
would be to see which elements have zero derivative. But, then, derivative with respect to which variable? Of course,
I should consider derivative with respect to all variables because 1/x has 0 derivative with respect to y. But, the problem
with this approach (although it works) is that it is computationally very expensive in reality. Please note that in practice
I have very long vectors and need to repeat this process many times, but the vector considered here is just an example. Another,
idea is to use the command X = findSymType(expr,'constant') but it considers all constants and does not do what I want.
Any idea?
Thanks in advance!
Babak

Accepted Answer

Walter Roberson
Walter Roberson on 11 Feb 2022
syms x y
f = [x^2+y; 2; 3*x^4*y^2; 5; 1/x; 12]
f = 
f(hasSymType(f, 'variable'))
ans = 
However, if you were considering derivative 0, then that raises the question of what to do about π -- and for that matter, whether your criteria is "no variables" or if you would want to retain an expression such as 1 + sqrt(2) (constants but expression).
Then too the question arises about what should be done with expressions such as int(x^2,x,3,5) as those are actually constants: if an expression includes a variable but only in bound form such as in int() or symprod() or symsum() then those expressions are actually constants.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!