首页 > 解决方案 > 将matlab函数输出(单元格数组)转换为逗号分隔的列表,没有临时单元格数组

问题描述

如标题所示,作为 matlab 函数输出的元胞数组如何在不使用临时数组的情况下直接转换为逗号分隔的列表?

即,我知道你可以写

% 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

我正在寻找一种允许我以类似的方式执行此操作的方法

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

以便它可以在不允许使用临时参数的匿名函数中使用。例子:

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

这怎么可能实现?我认为在使用运算符'{:}'时必须调用一个函数,但它会是哪一个?

编辑澄清:

这个问题被标记为可能重复的答案中的解决方案不能解决问题,因为在创建逗号分隔列表时 subsref 不是 {:} 的替代品。

例子:

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

是(错误地)

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

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

返回(正确)

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

标签: matlabcellinline

解决方案


好的,答案是(请参阅上面评论中 Sardar Usama 的评论)替换

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

经过

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

推荐阅读