比较matlab中的单元格

时间:2013-06-12 21:52:14

标签: arrays matlab

让strCellArr成为4000 * 1的单元格数组。每个单元格都是一个字符串。

判断每个单元格是否包含长度为100的字符串的最快方法是什么。

换句话说,我想要的东西和

一样
a= true;
For (i =0; i =length(strCellArr); i++)
    if length(strCellArr{i}) ~= 100
         a = false;
    end
end

相关问题:

我可以使用

将数组转换为4000 * 100的字符数组
charArr = char(strCellArr);

但是,这会在没有100个字符的行中引入空格。因此,如果第34行只有30个字符。然后

charArr(34)(50)

将返回一个空格。

在我的情况下(A,T,C或G),如何检查每个字符是否只包含某些字符。有没有办法不使用for循环呢?

3 个答案:

答案 0 :(得分:6)

哦,我只是喜欢那些以“最快的方式......”开头的问题。

以下是一些替代方案和比较:

% Initalize

map = 'CATG';     
strCellArr = cellfun(@(x) map(randi(4,100,1)),cell(4000,1), 'UniformOutput', false);


% Your original method 
tic
a = true;
for el = strCellArr
    if length(el{1}) ~= 100
         a = false;
         break;
    end
end
toc

% My solution 
tic
a = all(cellfun('length', strCellArr) == 100);
toc

% Dang Khoa's method
tic
a = all( cellfun(@(x) length(x) == 100, strCellArr) );
toc

% Engineero's method
tic
a = all(cellfun(@length, strCellArr) == 100);
toc

结果:

Elapsed time is 0.001158 seconds. % loop
Elapsed time is 0.000455 seconds. % cellfun; string argument
Elapsed time is 0.031897 seconds. % cellfun; anonymous function
Elapsed time is 0.006994 seconds. % cellfun; function handle

鲜为人知的事实:cellfun的字符串输入是指直接构建到cellfun二进制文件中的函数,因此不需要评估匿名函数。换句话说,cellfun不必在每次迭代中都通过MATLAB解释器,使 raging 快速运行:)

现在,问题的第二部分:

% Engineero
tic
A = 'ATCG';
all(all(ismember(char(strCellArr), A)));
toc

% My solution 
tic
C = char(strCellArr);
~any(C(:)==' ');
toc

结果:

Elapsed time is 0.061168 seconds. % ismember
Elapsed time is 0.005098 seconds. % direct comparison to whitespace

这种差异的产生是因为ismember是在MATLAB m代码中实现的,并且充满了用户友好性的代码(错误检查,错误,警告等),精心设计的概括,循环结构等等。其他一切都是性能损失。

由于我们事先知道只有空格会在将其转换为char时添加到数组中,我们必须明确检查是否出现'A''C''T''G',但仅限于 abscence 。意思是,只需寻找那些空间:)

毋庸置疑,这些时间所有几乎可以忽略不计,而这实际上更多是精神手淫而非真正有用。但它的乐趣! :)

答案 1 :(得分:3)

对于您的第一个问题,您可以使用all(cellfun(@length, strCellArr) == 100),这将为" true"返回1如果单元格中的每个元素都有100个元素的长度。

对于第二个问题,您可以all(ismember(charArr, A))使用A = ['A', 'T', 'C', 'G']。有关详情,请参阅allismember上的文档。

答案 2 :(得分:3)

对于你的第一个问题:这听起来像是cellfun的工作。 cellfun允许您对单元格数组中的每个单元格进行操作。 (顺便说一句,arrayfun允许你在常规数组上执行相同操作)。 (请注意,您的原始代码不是MATLAB语法,尤其是for循环。)

所以你可以做类似

的事情
res = cellfun(@(x) length(x) == 100, strCellArr);

此处res将是logical,因为==条件将评估为0或1.然后,您可以看到all的结果是否为1,即,strCellArr中的所有字符串长度为100:

a = all(res);
if a == 0
    disp('One or more strings does not have 100 characters!');
else
    disp('All strings have 100 characters!');
end