Search code examples
matlabequationsymbolic-math

How to count the number of symbolic variables in an equation in MATLAB?


Suppose I have three equations like [x1+x2+x3, -x1, x1+x2+1].

Is there any function in MATLAB by which I can count the number of symbolic variables of each of these equations?

Thanks in advance.


Solution

  • If you want to know the total number of variables, you can use symvar as follows:

    >> syms x1 x2 x3                  % define symbolic variables
    >> y = [x1+x2+x3, -x1, x1+x2+1]   % define symbolic equation
    >> numel(symvar(y))               % get number of sumbolic variables
    ans =
         3
    

    To obtain the number of variables of each equation, you can use the following, as suggested by @SardarUsama:

    >> arrayfun(@(t) numel(symvar(t)), y)
    ans =
         3     1     2
    

    This loops over the equations and gets the number of variables of each.