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!