Problem with a matlab question
1 view (last 30 days)
Currently doing revision for a MATLAB module next year. Was attempting a question and was hoping for some help it.
I am asked to consider this Taylor series expansion:
S(x,n)=(x-1) - 1/2(x-1)^2 + 1/3(x-1)^3 - 1/4(x-1)^4 +...+ ((-1)^(n-1))*(1/n)*(x-1)^n
From this write a matlab function that, given the values of x and n, returns the value of S(x,n).
Obviously, I do not want someone to do the problem for me and just copy it. I would just like some advise and how to represent this as a script.
Thank you in advance for your time
Evan on 5 Aug 2013
Edited: Evan on 5 Aug 2013
There are multiple ways you can do this. The first involves a for loop and, while it might require more lines of code, is probably a more basic route to follow and might be beneficial for getting into the swing of MATLAB.
The second way, however, is much more compact and takes advantage of MATLAB's strengths: array operations. A hint: in order to do this, the element-by-element array operators (.* ./ .^) will be needed instead of the normal matrix arithmetical operators (* / ^).
For either method, what you are needing to do is the same: you want to apply some arithmetic operation to all integer values from 1 to n, then you want to add up the results.
If that's too vague or you think an example might help, just let me know.
More Answers (1)
Iain on 5 Aug 2013
Its hard to give you help without giving you the answer to this one.
Option 1. Recursively call the script.
S = func(x,n)
function s = func(x,n) if n >0 s = "this term" + func(x,n-1); else s = "this term"; end
Option 2. Vectorize the summation
n = 1:n;
S = sum((-1).^(n-1) .* 1./n .*(x-1).^2 ))