Generate a list of array components interpreted as a comma separated list
显示 更早的评论
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!
回答(1 个)
James Tursa
2017-2-9
编辑:James Tursa
2017-2-9
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 个评论
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
2017-2-9
James Tursa
2017-2-9
编辑:James Tursa
2017-2-9
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)
类别
在 帮助中心 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!