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

2 次查看(过去 30 天)
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 个评论
Geoff
Geoff 2012-5-10
Symbolic expressions are not native to computer hardware, whereas simple arithmetic is.
Anthony
Anthony 2012-5-14
I'm summing symbolic expressions in both cases. The only difference is that in one I use "sum" and in the other I use "+"

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2012-5-10
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 个评论
Anthony
Anthony 2012-5-14
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).

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by