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
2012-5-10
Symbolic expressions are not native to computer hardware, whereas simple arithmetic is.
回答(1 个)
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!