I wonder if anyone has any suggestions to improve the performance, presentation, and/or output of the following MATLAB code?
I have written a program to approximate sin x using a partial sum
((-1)^n)*(x.^((2*n)+1))/(factorial((2*n)+1))
using the methods LS and SL. For LS, I have computed and summed the terms from the largest term first to the smallest term last. For SL, I have done the calulation in the reverse order.
Here is my function:
function ret = taylorsin(x,n)
ret = ((-1)^n)*(x.^((2*n)+1))/(factorial((2*n)+1));
end
and my short code:
function ret = partialsum(x,n,log)
ret = 0;
if log == 1
for i = 0:1:n
ret = ret + taylorsin(x,i);
i=i+1;
end
elseif log == 0
for i = n:-1:0
ret = ret + taylorsin(x,i);
i = i+1;
end
end
end
Thanks for any input.
On first viewing, a couple of things stand out:
ii
)log
)ii=ii+1
is not necessary)taylorsin
function in the loop (function calls to non-built-in functions can be hard to JIT)log
(this WILL bite you)So, a quick improvement would be:
But given that the outcomes of the computations in the loop are the same (just the summation order is different), you can vectorize the whole thing: