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

2 visualizaciones (últimos 30 días)
Anthony
Anthony el 10 de Mayo de 2012
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 comentarios
Geoff
Geoff el 10 de Mayo de 2012
Symbolic expressions are not native to computer hardware, whereas simple arithmetic is.
Anthony
Anthony el 14 de Mayo de 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 "+"

Iniciar sesión para comentar.

Respuestas (1)

Walter Roberson
Walter Roberson el 10 de Mayo de 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 comentarios
Walter Roberson
Walter Roberson el 11 de Mayo de 2012
Good point about symsum()
Anthony
Anthony el 14 de Mayo de 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).

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by