Question

I'm trying to write a generic function for finding the cosine of a value inputted into the function. The formula for cosine that I'm using is:

        n
cosx = sum((-1)^n*x^(2n)/(2n)!)
       n=1

I've looked at the matlab documentation and this page implies that the "sum" function should be able to do it so I tried to test it by entering:

sum(x^n, n=1..3)

but it just gives me "Error: The expression to the left of the equals sign is not a valid target for an assignment".

Is summing an infinite series something that matlab is able to do by default or do I have to simulate it using a function and loops?

Was it helpful?

Solution

Well if you want to approximate it to a finite number of terms you can do it in Matlab without toolboxes or loops:

sumCos = @(x, n)(sum(((-1).^(0:n)).*(x.^(2*(0:n)))./(factorial(2*(0:n)))));

and then use it like this

sumCos(pi, 30)

The first parameter is the angle, the second is the number of terms you want to take the series to (i.e. effects the precision). This is a numerical solution which I think is really what you're after.

btw I took the liberty of correcting your initial sum, surely n must start from 0 if you are trying to approximate cos

If you want to understand my formula (which surely you do) then you need to read up on some essential Matlab basics namely the colon operator and then the concept of using . to perform element-wise operations.

OTHER TIPS

In MATLAB itself, no, you cannot solve an infinite sum. You would have to estimate it as you suggested. The page you were looking at is part of the Symbolic Math toolbox, which is an add-on to MATLAB. In particular, you were looking at MuPAD, which is rather similar to Mathematica. It is a symbolic math workspace, whereas MATLAB is more of a numeric math workspace. If you own the Symbolic Math toolbox, you can either use MuPAD as you tried to above, or you can use the symsum function from within MATLAB itself to carry out sums of series.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top