Creating recurrence relation and plotting relative error
9 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (1 件)
Guillaume
2015 年 2 月 21 日
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 件のコメント
Guillaume
2015 年 2 月 22 日
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.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!