Series generated by recursive formula

31 ビュー (過去 30 日間)
mutt
mutt 2013 年 2 月 7 日
Suppose each value in a series depends on its immediate predecessor, say, x(n) == j*x(n-1) + k*y(n)
What is the most efficient way to express this in MATLAB?

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 7 日
編集済み: Azzi Abdelmalek 2013 年 2 月 7 日
y=0:10 % Example
k=10
x(1)=0
for n=1:10
x(n+1)=j*x(n)+k*y(n+1)
end
  4 件のコメント
Thorsten
Thorsten 2013 年 2 月 7 日
No. It would be possible only if you could transform your equation such that x(n) does NOT belong on its predecessor.
For large n the computation will be faster if you preallocate x such as
x = nan(1, Nmax);
for x = 1:Nmax
:
end
José-Luis
José-Luis 2013 年 2 月 7 日
You could always write a recursive function. Having said that, I have some gripes against those as I found them difficult to understand and generally not worth the effort.

サインインしてコメントする。


José-Luis
José-Luis 2013 年 2 月 7 日
編集済み: José-Luis 2013 年 2 月 7 日
You could always write a recursive function, but I would much rather use the for loop as it is much simpler to understand, IMO, and probably faster too.
Start by defining an anonymous function:
myFun = @(x) 4.*x + sin(x); %the function you want to apply to the previous value
And placing the following function in your path:
function [your_mat] = someFunction(n,myFun,start_val)
temp_val = start_val;
your_mat = recfun(n,temp_val);
function [temp_val] = recfun(n,temp_val) %here be recursion
if n == 0
temp_val = [];
else
temp_val = [temp_val myFun( recfun( n-1 , temp_val(end) ) ) ];
end
end
end
Where n is the number of evaluations and start_val is your starting value. And you could run it from the command line as follows:
your_mat = someFunction(10,myFun,5); %10 reps, starting value of 5
your_mat will be a matrix where every value is dependent on the previous one. Note that you would still need to modify the code to make it do exactly what you want.

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by