How to create recursive function handle efficiently
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
John D'Errico
le 29 Juil 2017
Modifié(e) : John D'Errico
le 29 Juil 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.
Réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!