Reputation: 632
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.)
Upvotes: 2
Views: 153
Reputation: 22215
At the risk of stating the obvious, this can be impemented as a for loop.
Here is one implementation.
function Y = cumsum( X, N )
if nargin < 2, N = 1; end
YDims = size( X ); NDim = YDims(N); Y = sym( zeros( YDims ) );
XIdx = substruct( '()', repmat( {':'}, 1, ndims( X ) ) );
YIdx = substruct( '()', repmat( {':'}, 1, ndims( Y ) ) );
for i = 1 : NDim
XIdx.subs{N} = 1 : i;
YIdx.subs{N} = i;
Y = subsasgn( Y,
YIdx,
sum( subsref( X, XIdx ), N )
);
end
end
Copy this in your symbolic installation folder1 as cumsum.m and your above script will work as in matlab.
1: (in my case this was ~/.octave/symbolic-2.9.0/@sym/cumsum.m because I have set my pkg prefix as ~/.octave )
Upvotes: 2
Reputation: 19689
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
Upvotes: 6