Creating recurrence relation and plotting relative error

9 views (last 30 days)
I need to create a recurrence relation that looks like this T[n](x)=(2x)*T[n-1](x)-T[n-2](x) for n=1-25. I need to compute T[n](1/2) and am given that T[0](x)=1 and T[1](x)=x. After calculating the recurrence relation, I need to compare the values to the theoretical value of T[n](1/2)=cos(n*pi/3) and plot the relative error. I am new to MATLAB and have no idea how to do any of this.
I have tried
Tn=@(n) (2*1/2+0)*T(n-1)-1*T(n-2) T(0)=1 T(1)=x for n=2:25 recurrence=T(n) relerror2=abs(theoretical-recurrence)/abs(theoretical) end
and keep getting the error:
Attempted to access T(0); index must be a positive integer or logical.
Error in Problem6 (line 13) T(0)=1

Answers (1)

Guillaume
Guillaume on 21 Feb 2015
Matlab indices start at 1. Therefore T(0) is illegal. If you want to keep most of your code, simply offset the n up by 1, so that T(1) = 0 and T(2) = x) and stop your iteration at 26.
This is not however how you write a true recurrent functions. Here's one way you would write the Fibonacci recurrence: f(n) = f(n-1) + f(n-2) with f(0) = 1 and f(1) = 1:
function f = fib(n)
if n == 0
f = 1;
elseif n == 1
f = 1;
else
f = f(n-1) + f(n-2);
end
end
You can use this as a guide to write your own recurrent function.
  8 Comments
Tiffany Morris
Tiffany Morris on 22 Feb 2015
Okay, so that at least gives me output now and makes a fair amount of sense to me. Thank you. Now, I need to compute the relative error between that recursive function and T[n](1/2)=cos(n*pi*3). How would I do that? Should I put
theoretical=cos((n-1)*pi*3)
inside the "for" loop? I put (n-1) since I had to increase the index of the recursive relation by 1. If that is the case, then where should I put the case for n=1 i.e. cos(1*pi/3)? I then need to find the relative error between the recursive and theoretical functions and plot that error. How would I do that? I truly do appreciate all the help you have given me. Thank you again.
Guillaume
Guillaume on 22 Feb 2015
It would be
theoretical(n) = cos((n-1)*pi/3);
That is you want to store the result of each iteration. And, yes it goes into the loop. A good practice is also to preallocate the array before the loop, the same way I've done for T, using zeros.
You calculate the error by subtracting the two values, dividing by the true value and storing the result into a third array. You can actually do that after the loop using memberwise operation (i.e. ./). You can then plot all of these arrays any way you want.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!