Generate a list of array components interpreted as a comma separated list
Mostrar comentarios más antiguos
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!
Respuestas (1)
James Tursa
el 9 de Feb. de 2017
Editada: James Tursa
el 9 de Feb. de 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 comentarios
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
el 9 de Feb. de 2017
James Tursa
el 9 de Feb. de 2017
Editada: James Tursa
el 9 de Feb. de 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)
Categorías
Más información sobre Operators and Elementary Operations 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!