Search code examples
octavesymbolic-mathcumsum

Why is cumsum not working with symbolic vectors?


I wrote a small Octave script involving cumsum on symbolic vectors, which I expected to work but unfortunately, it does not. Here's the code:

pkg load symbolic
n = 3;
syms q x
q = sym('q', [n 1]);
x = sym('x', [n 1]);
cumsum(q - x)

Instead of the expected result, I get:

error: cumsum: wrong type argument 'class'

Why does this happen? Would it work with Matlab Symbolic Toolbox? (I don't have it so I cannot test, unfortunately.)


Solution

  • That's just because cumsum written in Octave is not supported for symbolic elements as indicated by the error message. Your code gives the following in MATLAB:

    ans =
                         q1 - x1
               q1 + q2 - x1 - x2
     q1 + q2 + q3 - x1 - x2 - x3
    

    You can do something like this:

    t1 = q-x;
    t2 = triu(ones(numel(t1)));
    sum(repmat(t1,1,3).*t2).'
    % repmat is necessary here because implicit expansion is also not 
    % supported for matrices of class sym in Octave
    
    

    Above code in Octave and MATLAB gives the following respectively:

    ans = (sym 3×1 matrix)
    
      ⎡            q₁₁ - x₁₁            ⎤
      ⎢                                 ⎥
      ⎢      q₁₁ + q₂₁ - x₁₁ - x₂₁      ⎥
      ⎢                                 ⎥
      ⎣q₁₁ + q₂₁ + q₃₁ - x₁₁ - x₂₁ - x₃₁⎦
    
    ans =
                         q1 - x1
               q1 + q2 - x1 - x2
     q1 + q2 + q3 - x1 - x2 - x3