Generate a list of array components interpreted as a comma separated list
Afficher commentaires plus anciens
Hi all,
I want to define a function handle, say
fun = @(C) F(C(1),C(2),C(3),C(4),C(5));
but this C array does not always have the same size and also it's size may get quite large. Thus, I'm looking for a more compact and automated way to write the above expression.
Any ideas?
Thanks!
Réponses (1)
James Tursa
le 9 Fév 2017
Modifié(e) : James Tursa
le 9 Fév 2017
If C can be passed in as a cell array, you could do this:
fun = @(C) F(C{:});
The C{:} part will expand as a comma separated list. However, this may not be practical if the size of C could be "quite large" as you put it. In such a case, it would probably be best for the function F to handle the breakout of C inside the function, rather than forcing the cell elements of C into a comma separated list as explicit arguments.
3 commentaires
The MATLAB documentation explains three ways to create a comma separate list: write out the variables with commas, from a cell array, or from a structure. This answer, using a cell array, is the simplest solution that fulfills the original question's requirements.
Apostolos Psaros
le 9 Fév 2017
James Tursa
le 9 Fév 2017
Modifié(e) : James Tursa
le 9 Fév 2017
Kind of ugly, but you could use eval for this, e.g.
% fun = @(C) F(C(1),C(2),C(3));
args = sprintf('C(%d),',1:numel(c));
fun = eval(['@(C)F(' args(1:end-1) ')']);
(This is a kinder, gentler use of eval since it doesn't "pop" variables into the workspace)
Catégories
En savoir plus sur Operators and Elementary Operations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!