From: Tom Toner on
Hi

I have a vector
v=1:20;
and two index vectors
i1=[3 6 11 15];
i2=[5 9 12 19];

I am trying to find the elements between i1(k) and i2(k), k=1:4.
The results should be [4 7 8 16 17 18].

Could you please help me do it without loops?
Thanks,
Tom
From: Jos (10584) on
"Tom Toner" <nm2bean(a)yahoo.com> wrote in message <hm6mgl$ip1$1(a)fred.mathworks.com>...
> Hi
>
> I have a vector
> v=1:20;
> and two index vectors
> i1=[3 6 11 15];
> i2=[5 9 12 19];
>
> I am trying to find the elements between i1(k) and i2(k), k=1:4.
> The results should be [4 7 8 16 17 18].
>
> Could you please help me do it without loops?
> Thanks,
> Tom

Here is one approach:

% some data
v = 10*(1:20) ;
i1=[3 6 11 15];
i2=[5 9 12 19];
% engine
idx = zeros(size(v)) ;
idx(i1+1) = idx(i1+1) + 1 ;
idx(i2) = idx(i2) + 1 ;
result = find(mod(cumsum(idx),2)==1)
v(result)
hth
Jos
From: ade77 on
"Tom Toner" <nm2bean(a)yahoo.com> wrote in message <hm6mgl$ip1$1(a)fred.mathworks.com>...
> Hi
>
> I have a vector
> v=1:20;
> and two index vectors
> i1=[3 6 11 15];
> i2=[5 9 12 19];
>
> I am trying to find the elements between i1(k) and i2(k), k=1:4.
> The results should be [4 7 8 16 17 18].
>
> Could you please help me do it without loops?
> Thanks,
> Tom


Another solution is to use arrayfun:
v = 1:20;
m1 = [3 6 11 15];
m2 = [5 9 12 19];

data = arrayfun(@(x,y)v((x+1):(y-1)),m1,m2,'un',0);
data = cell2mat(data);
From: Tom Toner on
Hi Jos and ade77,

Thank you very much for the simple and effective methods.

Basically I was trying to obtain the positions of 1s between 0s at odd positions and 0s at enven positions (not between 0s at even positions and 0s at odd positions) of a large random vector with elements of only 0 and 1, say 10000 or 100000 at length.

So I wrote a code to test your methods as following:

clear all
% obtain i1 and i2
len = 100000;
v = randi([0 1],1,len);
i0 = find(v==0);
len0 = length(i0);
i1 = i0(1:2:len0);
i2 = i0(2:2:len0);
if length(i1)>length(i2)
i1(end) = [];
elseif length(i1)<length(i2)
i2(end) = [];
end
% Jos' method
tic
idx = zeros(1,len) ;
idx(i1+1) = idx(i1+1) + 1 ;
idx(i2) = idx(i2) + 1 ;
result1 = find(mod(cumsum(idx),2)==1);
toc
% ade77's method
tic;
data = arrayfun(@(x,y)((x+1):(y-1)),i1,i2,'un',0);
result2 = cell2mat(data);
toc

The results are:

Elapsed time is 0.031683 seconds.
Elapsed time is 0.745710 seconds.

The results are identical. But Jos' method is more efficient for a 1x100000 vector.
From: Siyi Deng on
On Feb 25, 12:28 pm, "Tom Toner" <nm2b...(a)yahoo.com> wrote:
> Hi
>
> I have a vector
>       v=1:20;
> and two index vectors
>       i1=[3 6 11 15];
>       i2=[5 9 12 19];
>
> I am trying to find the elements between i1(k) and i2(k), k=1:4.
> The results should be [4 7 8 16 17 18].
>
> Could you please help me do it without loops?
> Thanks,
> Tom

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

index = logical(cumsum(x));

v(index)