Search code examples
matlabsplitsymbolic-mathfactoring

Convert matlab symbol to array of products


Can I convert a symbol that is a product of products into an array of products?

I tried to do something like this:

syms A B C D;
D = A*B*C;
factor(D);

but it doesn't factor it out (mostly because that isn't what factor is designed to do).

ans =
A*B*C

I need it to work if A B or C is replaced with any arbitrarily complicated parenthesized function, and it would be nice to do it without knowing what variables are in the function.

For example (all variables are symbolic):

D = x*(x-1)*(cos(z) + n);
factoring_function(D);

should be: [x, x-1, (cos(z) + n)]

It seems like a string parsing problem, but I'm not confident that I can convert back to symbolic variables afterwards (also, string parsing in matlab sounds really tedious).

Thank you!


Solution

  • Use regexp on the string to split based on *:

    >> str = 'x*(x-1)*(cos(z) + n)';
    >> factors_str = regexp(str, '\*', 'split')
    factors_str = 
        'x'    '(x-1)'    '(cos(z) + n)'
    

    The result factor_str is a cell array of strings. To convert to a cell array of sym objects, use

    N = numel(factors_str);
    factors = cell(1,N); %// each cell will hold a sym factor
    for n = 1:N
        factors{n} = sym(factors_str{n});
    end