For loop in function handle

42 vues (au cours des 30 derniers jours)
Andy Tran
Andy Tran le 24 Juin 2020
Modifié(e) : Andy Tran le 28 Juin 2020
I want to creat a function with multiple variables, something like:
f = @(x) = f1(x) + f2(x) + ... + fn(x)
where x is a n-dimensional vector which can be define by user. The number of functions f1,f2,..,fn can be define by user, too.
The question is can i use a for loop in function handle to define f according to the length of vector x?

Réponses (2)

Stephen23
Stephen23 le 24 Juin 2020
Modifié(e) : Stephen23 le 24 Juin 2020
You can simply store function handles in a cell array of any size and use cellfun. No loop required.
>> C = {@sin,@sqrt,@pow2};
>> F = @(x) sum(cellfun(@(f)f(x),C));
>> F(3)
ans = 9.8732
compare with:
>> sin(3) + sqrt(3) + pow2(3)
ans = 9.8732
If you really want to use a for loop then you would need to write the function in an Mfile, e.g.:
function out = myfun(x)
out = 0;
C = {@sin,@sqrt,@pow2};
for k = 1:numel(C)
out = out + C{k}(x);
end
end
  8 commentaires
Stephen23
Stephen23 le 28 Juin 2020
"How can i define function C with unknown number of variables (i call it as N), others parameters are generate corresponding to N."
Rather than creating lots of variables the simple and efficient MATLAB way is to use one vector/matrix/array.
Your approach is making this much more complex than it needs to be.
Andy Tran
Andy Tran le 28 Juin 2020
Modifié(e) : Andy Tran le 28 Juin 2020
Yes i know it. But further i need to find the maximum of the function C minus D (which is a linear function acording to p_n) for each p_n. The way im trying to do is using anonymous function and so that i think i need to treat p_n as a variable. Do you have other suggestion?
Thanks for helping me out.

Connectez-vous pour commenter.


Walter Roberson
Walter Roberson le 26 Juin 2020
The question is can i use a for loop in function handle to define f according to the length of vector x?
NO. Anonymous functions cannot use for .
Anonymous functions can use arrayfun() and cellfun() and can use function calls that process the resulting arrays.

Catégories

En savoir plus sur Shifting and Sorting Matrices 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!

Translated by