【问题标题】:Matlab: jsconencode with function handlesMatlab:带有函数句柄的 jsconencode
【发布时间】:2019-08-01 11:55:23
【问题描述】:

考虑 matlab 中的以下元胞数组

    mycell = {@sin,@cos}

它有两个元素,每个元素都是一个函数句柄。 现在当我打电话时

    jsonencode(mycell)

我收到错误“无法将类 function_handle 的对象编码为 JSON 格式的文本”。 有没有办法通过强制 Matlab 使用函数句柄的 func2str() 的输出来解决这个错误?

【问题讨论】:

  • 你期望结果是什么?...["sin", "cos"]?

标签: matlab


【解决方案1】:

您可以在对单元格进行编码之前替换函数句柄:

function c = prepare_cell( c ) 
    % replace function handles
    idx = cellfun(@(x) isa(x, 'function_handle'), c);
    for ii = find(idx)
        c{ii} = func2str(c{ii});
    end
    % repeat for cells in cells
    idx = cellfun(@(x) iscell(x), c);
    for ii = find(idx)
        c{ii} = prepare_cell(c{ii});
    end
end

用法:

>> c = {@sin, @cos, 1, 2, {@sin, @cos, 1, 2}};
>> jsonencode(prepare_cell(c))

ans =

    '["sin","cos",1,2,["sin","cos",1,2]]'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多