-2

As by the title, how can a cell array that is the output of a matlab function be directly turned into a comma-separated list without using a temporary array?

I.e., I know you can write

% functioning code
tmp = cell(1,3); % function that makes a temporary cell_array;
b = ndgrid(tmp{:}); % transform tmp into a 
% comma-separated list and pass into another function

I am looking for a way that allows me to do this in a way like

% non functioning code
b = ndgrid( cell(1,3){:} );

so that it can be used within an anonymous function, where no temporary arguments are allowed. Example:

fun = @(x)accept_list( make_a_cell(x){:} );

How could this be achieved? I would think that there must be a function invoked when the operator '{:}' is used, but which one would it be?

EDIT for clarification:

The solution in the answer which this question was tagged to possibly be a duplicate of does not solve the problem, because subsref is not a replacement for {:} when creating a comma-separated list.

Example:

a = {1:2,3:4}
[A1,A2] = ndgrid(subsref(a, struct('type', '{}', 'subs', {{':'}})));

is (wrongly)

A1 =
     1     1
     2     2
A2 =
     1     2
     1     2

but

a = {1:2,3:4}    
[A1,A2] = ndgrid(a{:});

returns (correctly)

A1 =
     1     1
     2     2
A2 =
     3     4
     3     4

2 Answers2

0

Ok, the answer is (see comments of Sardar Usama in the comments above) to replace

fun = @(x)accept_list( make_a_cell(x){:} );

by

tmpfun = @(cell_arg, fun_needs_list)fun_needs_list( cell_arg{:} );
fun = @(x)tmpfun(make_a_cell(x), accept_list);
0

You can use the string ':' as an index. This syntax always looks weird to me but it works in many cases. In your example

tmp = cell(1,3);
b = ndgrid(tmp{:})

b =

   Empty array: 0-by-0-by-0

    b = ndgrid( cell(1,3){:} )
Error: ()-indexing must appear last in an index expression.

Now if you create a dummy variable say s = {':'}; Then you can get around the error by doing this:

b = ndgrid( cell(1,3){s{1}} )

b =

   Empty array: 0-by-0-by-0

Another option is to simply use the':' directly. b = ndgrid( cell(1,3){':'} );

Here is an example using num2cell

A = reshape(1:12,4,3);
A(:,:,2) = A*10;
a = {A, 1};
num2cell(a{':'})

ans(:,:,1) = 

    [4x1 double]    [4x1 double]    [4x1 double]


ans(:,:,2) = 

    [4x1 double]    [4x1 double]    [4x1 double]
a = {A, 2};
num2cell(a{':'})

ans(:,:,1) = 

    [1x3 double]
    [1x3 double]
    [1x3 double]
    [1x3 double]


ans(:,:,2) = 

    [1x3 double]
    [1x3 double]
    [1x3 double]
    [1x3 double]
Matt
  • 2,554
  • 2
  • 24
  • 45