Why is sum() slow on a matrix of symbolic expressions?

2 views (last 30 days)
I have a vector A of symbolic expressions and I need to create a new symbolic expression that is the sum of the elements of A. When I try doing
f=sum(A);
mupkern runs out of memory and gets killed by the OS. However, after some experimentation, I realized that the following finishes quickly:
f=0;
for i=1:n
f=f+A(i);
end
What is going on here?
I'm running Matlab R2010a on a Linux machine.
Here is some sample code to illustrate:
n=5000;
AA=cell(n,1);
for i=1:n
AA{i}=sprintf('a%d',i);
end
A=sym(AA);
f=sum(A); % takes about 7 minutes on my machine
g=0;
for i=1:n % takes less than a minute on my machine
g=g+A(i);
end
  2 Comments
Geoff
Geoff on 10 May 2012
Symbolic expressions are not native to computer hardware, whereas simple arithmetic is.
Anthony
Anthony on 14 May 2012
I'm summing symbolic expressions in both cases. The only difference is that in one I use "sum" and in the other I use "+"

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 10 May 2012
sum() applied to symbolic expressions is primarily for symbolic expression of indefinite summation. For example, finding the formula for the sum of 1/n^2 over a span of integers. When one is just wanting a total over a specific number of terms, then addition is the operator to use.
  3 Comments
Anthony
Anthony on 14 May 2012
Alexander, thank you for trying the example. Did the "sum" method and the "+" method take about the same amount of time to finish? It might have been more illustrative if the symbolic expressions in the elements of A were more complicated. This is the case in my application, but I simplified it for the example (since the difference in execution was still significant on my machine).

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!