【问题标题】:Transform matlab function output (cell array) into comma separated list without temporary cell array将matlab函数输出(单元格数组)转换为逗号分隔的列表,没有临时单元格数组
【发布时间】:2018-06-25 10:22:36
【问题描述】:

如题,作为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

【问题讨论】:

  • 为什么需要单线?您认为您会获得哪些额外优势?
  • 我在问题下方的编辑中添加了一些说明。不幸的是,建议的解决方案不起作用。
  • 所以创建一个临时匿名函数来调用实际的匿名函数。我认为没有任何真正需要单线

标签: matlab cell inline


【解决方案1】:

好的,答案是(参见上面 cmets 中 Sardar Usama 的 cmets)替换

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);

【讨论】:

    【解决方案2】:

    您可以使用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]
    

    【讨论】:

    • 这很有趣,谢谢!不幸的是,它只适用于某些功能。它不与例如num2cell.
    • @SteffenWolp 只要值正确,它就可以与num2cell 配合使用。
    • 好的,对。我的想法是,例如,ndgrid( num2cell(a){':'} ) 不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2012-06-14
    相关资源
    最近更新 更多