How can I create multiple function handles in a for loop?
Mostrar comentarios más antiguos
Hello to everyone!
I am trying to create multiple function handles with a for loop. For example:
mymat = 1:10;
for t = 1:length(mymat)
fun_t = (@) x^2-mymat(t)*x+mymat(t);
end
I would like to have 10 function handles like:
fun_1 = (@) x^2-1*x+1
...
fun_10 = (@) x^2-10*x+10
How can I do this? Would it be more convenient to use a matrix or an array with all the functions together?
Thank you very much and have a nice weekend!
2 comentarios
"I would like to have 10 function handles like"
You might "like to have" them all named like that, but that would be very bad data design:
"Would it be more convenient to use a matrix or an array with all the functions together?"
Yes, it would be much more convenient. It would also be much more efficient, easier to debug, etc.
For example, use a cell array to store them:
But why are you creating lots and lots of separate functions like that, when you could create one that operates on the entire matrix at once? It seems like something that would be better implemented as one function.
What are you actually trying to achieve?
Respuesta aceptada
Más respuestas (2)
The best would be to just have a matrix-valued function,
fun=@(x) x.^2-mymat(:).*x+mymat(:)
but you could make a cell array of scalar functions as well,
for t = 1:length(mymat)
c=mymat(t);
fun{t} = @(x) x^2-c*x+c;
end
1 comentario
Carles
el 10 de Mzo. de 2025
Diego Caro
el 10 de Mzo. de 2025
Store your function handles in a cell array.
my_mat = 1:10;
my_handles = cell(size(my_mat));
for t = 1:length(my_mat)
my_handles{t} = @(x) x.^2 - my_mat(t).*x + my_mat(t);
end
1 comentario
Matt J
el 10 de Mzo. de 2025
Note that I already gave this as part of my answer 3 days ago. Also, it is not efficient to define the functions with the syntax,
@(x) x.^2 - my_mat(t).*x + my_mat(t);
because this causes the function handle to store the entire array my_mat which is not needed. It is for this reason that I extracted my_mat(t) to a separate variable,
c=mymat(t);
fun{t} = @(x) x^2-c*x+c;
Categorías
Más información sobre Spline Postprocessing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

