Reputation: 3943
I need to return matches from a large cell array given one row to match. I wrote this code, but it seems like it shouldn't be this challenging - the code feels overwrought. What's the right way to do this?
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
Upvotes: 0
Views: 121
Reputation: 38032
How about
locations = find( ...
arrayfun(@(ii) isequal(haystack(ii,:), needle), 1:size(haystack,1)) );
not simpler per se, but it prevents a repmat
:)
In short, I don't think there is a "short" way to do what you want, because what you want is actually already really specific and hard to capture in generic operators. It's normal that under such circumstances, you'll need to do some more coding yourself.
By the way, it looks like your inputs are not cells at all -- why else would you need {needle}
and mat2cell()
? If they're not cells, there are much simpler methods to get where you want (bsxfun
, intersect
, etc.)
Upvotes: 1