Thursday, February 25, 2010

Matlab: indexing by two bounds

OP.


Q: Suppose I have an array
v = 1:20
and two index bound vectors
i1 = [3 6 11 15];
i2 = [5 9 12 19];


I want to index the elements between i1(k) and i2(k)
so v(index) is [4 7 8 16 17 18]


A1:
index1 = cell2mat(arrayfun(@(x,y)(x+1:y-1),i1,i2,'uni',false));



A2:
s = (i2-i1) > 1;
x = zeros(size(v));
x(i1(s)+1) = 1;
x(i2(s)) = -1;

index2 = logical(cumsum(x));

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));