I have an assignment to find the taylor expansion of a number and I am having problems with functions in Matlab in evaluating a function for a given variable.
Code:
function [taylorO] = taylor2(func,n)
taylorO=0;
for i=0:n
func=diff(func);
taylorO=taylorO+func(0)/factorial(i)*pow(x,i);
end
I get this error:
123??? Subscript indices must either be real positive integers or logicals.
Error in ==> taylor2 at 9
taylorO=taylorO+func(0)/factorial(i)*pow(x,i);
What I see here if I have this correct is you give the function Taylor an array 'func' and a number of itterations 'n'.
you then go and determine the differences between adjacent values in the func array, and add the first element of func over i! multiplied by x.
am I reading this code correctly?
Edit: No I'm not, you're trying to pass in a function 'func' and the diff should give the derivative of 'func' I don't think that this is happening correctly.
The error you are seeing is due to the fact that the code sees the variable func as an array passed into your matlab function from the code that calls your Talor2 function. Since Matlab indexes all arrays starting at '1' rather than '0' func(0) is undefined and results in the error you see.
Now what I think you are trying to do is have func be a function along the lines of func(x)= x^2 + x -1 or some such thing....
the easiest way to do this and make sure everything is working is create a file, like your TaylorO file,
Code:
function [y] = func(x)
y=x^2 + x -1;
and then eliminate the func input from your Taylor2 function like this
Code:
function [taylorO] = taylor2(n)
Now your code should work. I think the main problem is that the func is not passing as you think it should.
Edit : Don't ever forget the best Matlab debug tool there is.... eliminate the semicolons at the end of your lines of code to get the results to print to the console window.... Doing this you can verify any variables and see exactly where your code stops working.