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!

Answers (1)

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 Comments

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.
Thanks for the answer. This could be useful in other cases, but it seems to not work in what I'm trying to do. Perhaps, if I show you where I'm trying to apply it, you could have another idea:
c = sym('c', [1 3]);
for i=1:3
F(i)=i^2*c(1)+i^2*c(2)-i*c(3); % Not important, just an arbitrary function
end
F=matlabFunction(F);
fun = @(C) F(C(1),C(2),C(3));
options = optimset('Display', 'off');
X = fsolve(fun, ones(1, 3), options)
And I want to keep the definition of fun this way and also run fsolve this way (see here why: https://www.mathworks.com/matlabcentral/answers/324229-using-fsolve-with-array-of-symbolic-expressions)
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)

Sign in to comment.

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Asked:

on 9 Feb 2017

Edited:

on 9 Feb 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!