就像标题一样,作为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
答案 0 :(得分:0)
好,答案是(请参见上面评论中的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);
答案 1 :(得分:0)
您可以使用string ':' as an index.这个语法在我看来总是很奇怪,但是在许多情况下仍然有效。在您的示例中
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.
现在,如果您创建一个虚拟变量,请说s = {':'};
,然后您就可以通过以下方法解决该错误:
b = ndgrid( cell(1,3){s{1}} )
b =
Empty array: 0-by-0-by-0
另一种选择是直接直接使用':'
。 b = ndgrid( cell(1,3){':'} );
以下是使用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]