Thursday, February 25, 2010

Matlab: ismember in every row

Q:
Suppose I have

x = [1 2 3 4 5 6 7 8 9; 11 12 13 14 15 16 17 18 19]

I want to find out which row contains [3 7 9]

A1:

% Generate some data;

y = randi(50,1000,9);
t = [3 7 9];
% ensure that at least the first row has our target;
y(1:2,:) = x;

% Engine;

% This method assumes that the target is ascendingly sorted.
t1 = [3 3.1 7 7.1 9]; % 3.1 and 7.1 is arbitrary;
b = histc(y,t1,2);
idx1 = find(all(b(:,[1 3 5]),2));


A2:

% Engine;
idx2 = find(all(any(bsxfun(@eq,y,shiftdim(t,-1)),2),3));

No comments: