Search code examples
matlabsymbolic-math

how to find a symbolic variable in a symbolic expression in matlab?


I have a vector of symbolic expressions like this in matlab:

 (p4*x15 - (p2*p3*x3*x5)/(p1*x2))/p22
 (p7*x11 + p20*x11 + p17*x16 + p19*x16 - p6*x4*x10)/p22

I'd like to find the expression(s) where e.g. 'x2' is present. Any idea how can I do that? Thanks!


Solution

  • Using your example

    syms p1 p2 p3 p4 p6 p7 p17 p19 p20 p22
    syms x2 x3 x4 x5 x10 x11 x15 x16
    s(1) = (p4*x15 - (p2*p3*x3*x5)/(p1*x2))/p22;
    s(2) = (p7*x11 + p20*x11 + p17*x16 + p19*x16 - p6*x4*x10)/p22;
    

    you can use symvar:

    v = arrayfun(@(x)any(symvar(s)==x2),s);
    

    or you can use strfind:

    v = arrayfun(@(x)~isempty(strfind(char(x),'x2')),s);