我试图用MATLAB编码器工具箱下面的代码转换成C:
function [idx] = list_iterator(compare, list)
idx = nan(length(list));
for j = 1:length(list)
idx(j) = strcmp(compare, list{j});
end
list
是字符串的一个N×1单元阵列和compare
是一个字符串。码基本上比较list
的每个元素到compare
并返回1
如果两者相同,否则0
。 (我这样做是为了加快执行速度,因为N可以是相当大 - 约10〜20万台)
当我在命令窗口中运行codegen list_iterator
,我得到以下错误:
输入参数的类型“比较”函数“list_iterator”没有规定。使用-args或预处理语句来指定输入类型。
更多信息
误差在==> list_iterator线:1柱:18
代码生成失败:查看错误报告
使用代码生成错误
我知道我应该使用codegen
时指定类型的输入,但我不知道如何为字符串单元阵列做到这一点,其中的元素可以有不同的长度。字符串compare
也可以根据各自的函数调用不同的长度。
您可以使用该功能coder.typeof
指定大小可变的输入codegen
。从我了解你的榜样的,是这样的:
>> compare = coder.typeof('a',[1,Inf])
compare =
coder.PrimitiveType
1×:inf char
>> list = coder.typeof({compare}, [Inf,1])
list =
coder.CellType
:inf×1 homogeneous cell
base: 1×:inf char
>> codegen list_iterator.m -args {compare, list}
似乎是适当的。
如果检查出MATLAB编码器应用程序,它提供指定这些复杂的输入的图形手段。从那里,你可以将此导出到构建脚本来查看相应的命令行的API:
需要注意的是,当我试图与codegen
这个例子中,所产生的MEX并不比MATLAB更快。原因之一可能发生这种情况是因为该函数的主体是相当简单的,但大量的数据从MATLAB转移到生成的代码和背部。其结果,该数据传输开销可以支配的执行时间。移动更多的代码来生成MEX可以改善这一点。
有关性能无关codegen
思考,你应该使用idx = false(length(list),1);
而非idx = nan(length(list));
?前者是NX1逻辑矢量而后者是一个NxN矩阵双这里我们仅在list_iterator
写拳头柱。
有了您的原代码和compare = 'abcd'; list = repmat({'abcd';'a';'b'},1000,1);
此输入产生时间:
>> timeit(@()list_iterator(compareIn, listIn))
ans =
0.0257
修改你的代码返回一个矢量缩放下来:
function [idx] = list_iterator(compare, list)
idx = false(length(list),1);
for j = 1:length(list)
idx(j) = strcmp(compare, list{j});
end
>> timeit(@()list_iterator(compareIn, listIn))
ans =
0.0014
您也可以拨打strcmp
与细胞和字符数组这使得代码快还是:
function [idx] = list_iterator(compare, list)
idx = strcmp(compare, list);
>> timeit(@()list_iterator(compareIn, listIn))
ans =
2.1695e-05