Search code examples
matlaboctavesymbolic-math

Extract specific parts of a matlab/ octave symbolic expression?


How does one extract specific parts of an expression in Matlab/ Octave symbolic package? In XCAS, one can use indexing expressions, but I can't find anything similar in Octave/ Matlab.

For instance, with X = C*L*s**2 + C*R*s + 1, is there a way to get C*R*s by X(2) or the like?

It would be nice to do this with factors too. X = (alpha + s)*(beta**2 + s**2)*(C*R*s + 1), and have X(2) give (beta**2 + s**2).

Thanks!


Solution

  • children (MATLAB doc, Octave doc) does this but the order in which you write the expressions will not necessarily be the same. The order is also different in MATLAB and Octave.

    Expanded Expression:

    syms R L C s;
    X1 = C*L*s^2 + C*R*s + 1;
    partsX1 = children(X1);
    

    In MATLAB:

    >> X1
    X1 =
    C*L*s^2 + C*R*s + 1
    
    >> partsX1
    partsX1 =
    [ C*R*s, C*L*s^2, 1]
    

    In Octave:

    octave:1> X1
    X1 = (sym)
    
          2            
      C⋅L⋅s  + C⋅R⋅s + 1
    
    octave:2> partsX1
    partsX1 = (sym 1×3 matrix)
    
      ⎡       2      ⎤
      ⎣1  C⋅L⋅s   C⋅R⋅s⎦
    

    Factorised Expression:

    syms R C a beta s;   %alpha is also a MATLAB function so don't shadow it with your variable
    X2 = (a + s) * (beta^2 + s^2) * (C*R*s + 1);
    partsX2 = children(X2);
    

    In MATLAB:

    >> X2
    X2 =
    (a + s)*(C*R*s + 1)*(beta^2 + s^2)
    
    >> partsX2
    partsX2 =
    [ a + s, C*R*s + 1, beta^2 + s^2]
    

    In Octave:

    octave:3> X2
    X2 = (sym)
    
              ⎛ 2    2⎞            
      (a + s)⋅⎝β  + s ⎠⋅(C⋅R⋅s + 1)
    
    octave:4> partsX2
    partsX2 = (sym 1×3 matrix)
    
      ⎡                    2   2⎤
      ⎣C⋅R⋅s + 1   a + s   β + s ⎦