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

No comments: