我有一个(大)元胞数组,具有各种数据类型。例如,
myCell = { 1, 2, 3, 'test', 1 , 'abc';
4, 5, 6, 'foob', 'a', 'def' };
这可以包括更模糊的类型,例如 java.awt.Color
对象。
我想确保每一列中的数据属于同一类型,因为我想对其执行类似表的操作。然而,这个过程似乎很慢!
我目前的方法是用cellfun
获取类,用strcmp
检查
% Get class of every cell element
types = cellfun( @class, myCell, 'uni', false );
% Check that they are consistent for each column
typesOK = all( strcmp(repmat(types(1,:), size(types,1), 1), types), 1 );
% Output the types (mixed type columns can be handled using typesOK)
types = types(1, :);
% Output for the above example:
% >> typesOK = [1 1 1 1 0 1]
% >> types = {'double', 'double', 'double', 'char', 'double', 'char'}
我曾想过使用 cell2table
,因为出于同样的原因它会进行类型检查。但是,它没有给我想要的结果(严格来说,哪些列是哪些类型)。
有没有更快的方法来检查元胞数组列中的类型一致性?
编辑:我刚刚做了一些分析...
看来 types = cellfun( @class, ...)
行占用了 90% 以上的处理时间。 如果您的方法与我的方法略有不同,应该是那一行发生了变化,strcmp
非常快。
编辑:我很幸运对这个问题有很多建议,我把它们都整理成了一个 benchmarking answer用于性能测试。
最佳答案
要测试它是否可以更快地用于非常大的数组,但可能是这样的:
function [b] = IsTypeConsistentColumns(myCell)
%[
b = true;
try
for ci = 1:size(myCell, 2)
cell2mat(myCell(:, ci));
end
catch err
if (strcmpi(err.identifier, 'MATLAB:cell2mat:MixedDataTypes'))
b = false;
else
rethrow(err);
end
end
%]
end
这取决于 cell2mat
与您的字符串比较相比的速度有多快(即使此处未使用 cell2mat
的结果也是如此。
请注意,如果类型不一致(identifier: 'MATLAB:cell2mat:MixedDataTypes'
, message = 'All contents of the输入元胞数组必须具有相同的数据类型。'
)
编辑:限于 cellfun('isclass', c , cellclass) 测试
此处仅使用在 cell2mat
例程中内部执行的类型一致性检查:
function [consistences, types] = IsTypeConsistentColumns(myCell)
%[
ncols = size(myCell, 2);
consistences = false(1, ncols);
types = cell(1, ncols);
for ci = 1:ncols
cellclass = class(myCell{1, ci});
ciscellclass = cellfun('isclass', myCell(:, ci), cellclass);
consistences(ci) = all(ciscellclass);
types{ci} = cellclass;
end
%]
end
用你的测试用例 myCell = repmat( { 1, 2, 3, 'test', 1 , 'abc'; 4, 5, 6, 'foob', 'a', 'def' }, 10000, 5);
,
在我的计算机上使用 R2015b 大约需要 0.0123 秒......如果你想在第一个不一致的列上失败(这里我正在测试它们),它甚至可以更快
关于matlab - 获取元胞数组元素类类型的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48317906/