How to create recursive function handle efficiently

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 Commenti

John D'Errico
John D'Errico il 29 Lug 2017
Modificato: John D'Errico il 29 Lug 2017
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.
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....

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 29 Lug 2017

Commentato:

il 29 Lug 2017

Community Treasure Hunt

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

Start Hunting!

Translated by