2013-06-18 30 views
0

我需要从一个大单元阵列返回匹配,并给出一行匹配。我写了这段代码,但似乎不应该是这样的挑战 - 代码感觉过度。什么是正确的方法来做到这一点?MATLAB在单元阵列中匹配一行,提供了一个样本单元阵列

function locations= MatchRowInHaystack(haystack,needle) 
%Returns array locations: where needle matches haystack 
%Where Needle is a cell array of identifiers 
%And Haystack is a cell array of rows that may match needle. 
%Split haystack into cell arrays by row: 
rows=mat2cell(haystack,ones(size(haystack,1),1),size(haystack,2)); 
%Find row in haystack that matches needle row. 
locations=find(cellfun(@isequal,rows,repmat({needle},[numel(rows) 1]))); 
end 

回答

1

如何

locations = find(... 
    arrayfun(@(ii) isequal(haystack(ii,:), needle), 1:size(haystack,1))); 

本身并不简单,但它可以防止repmat :)

总之,我不认为这是一个“短”的方式做什么你想要的,因为你想要的实际上已经非常具体并且很难在泛型操作符中捕获。在这种情况下,你需要自己做更多的编码。

顺便说一下,它看起来像你的输入不是细胞 - 你还需要{needle}mat2cell()?如果他们是而不是单元格,有更简单的方法来获得您想要的位置(bsxfun,intersect等)