How to create recursive function handle efficiently

4 次查看(过去 30 天)
Assume the following:
u=[1 2 3];
W_in=[4 5 6]';
W=[1 2 3;4 5 6;7 8 9];
x=zeros(3,4); %initialization
x(:,1)=[1 2 3]';
How can I create a function handle such that:
x(:,i)=@(gamma) (1-gamma)*x(:,i-1)+gamma*(W*x(:,i-1)+W_in*u(i-1))
where gamma is a scalar between 0 and 1.
Since I CANNOT use double array to store function handle, I tried to use cell array to store function handles generated in the loop:
x=cell(1,4);
x{1}=[1 2 3]';
for i=2:4,
x{i}=@(gamma) (1-gamma)*x{i-1}(gamma)+gamma*(W*x{i-1}(gamma)+W_in*u(i-1))
end
However, I get the error with dimensions of W*x{i-1}(gamma),
also if I wish to set gamma to 0.4 and call x{2}(0.4), this cannot be done since I am only allowed to use integer index like x{2}(1),x{2}(2)...
Please help me on this, thank you so much!
  2 个评论
John D'Errico
John D'Errico 2017-7-29
编辑:John D'Errico 2017-7-29
Your question asks about how to define this for a non-integer index. However you have not defined how the recurrence would start for a non-integer "index". A recurrence makes mathematical sense only if you can start it in some way. Anyway, MATLAB does not allow non-integer indexes for arrays of any class. That includes cell arrays.
Your idea of a cell array of function handles is pretty much un-workable for what you are asking to do. Sorry. It may look pretty, but in practice the idea is worthless.
Instead, use a loop. I know it seems so terrible. But loops are fine in terms of efficiency. This silly cell array of function handles is still an implicit loop anyway. Using a loop allows you to start the recurrence simply. It allows you to deal with the initial value for that recurrence.
Finally, if you have a current MATLAB release, you might be able to use the memoize function to help you make your code more efficient.
Maple
Maple 2017-7-29
Thanks for your answer! if you use x{i}=@(gamma) (1-gamma)*x{i-1}+gamma*(W*x{i-1}+W_in*u(i-1)), and try to access x{2}(0.4) you will get [7.8 16 24.2]', which is what I want. However if you try x{3}(0.4), you get an error,that's the problem....

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by