필터 지우기
필터 지우기

Vectorized index generation based on multiple conditions

조회 수: 3 (최근 30일)
Haider Ali
Haider Ali 2019년 10월 2일
편집: Turlough Hughes 2019년 10월 2일
Hi all,
I have a huge column vector from which I need to extract specific values using vectorization instead of loops. The algorithm is like this:
Take first 5 values, check whether first or second value is greater than 48. If it is, remove those five values from the vector. Else remove first two values from the vector. Then take next five values and repeat.
This is the code based on loop:
data = randi([1 100],10000,1);
ind = ones(length(data),1);
for i = 1:5:length(data)
if (data(i) > 48 || data(i+1) > 48)
ind(i:i+4) = 0;
else
ind(i:i+1) = 0;
end
end
data_trunc = data(logical(ind));
What would the most effcient vectorized method to parse my vector?
Thanks
  댓글 수: 1
Turlough Hughes
Turlough Hughes 2019년 10월 2일
편집: Turlough Hughes 2019년 10월 2일
I'm sure one could do better but the following is defintely faster:
data = randi([1 100],10000,1);
data_trunc=reshape(data,[5,length(data)/5]); % convert to 5 by 2000 array
index_a=data_trunc(1,:)>48;
index_b=data_trunc(2,:)>48;
data_trunc(1:2,:)=[]; % delete rows 1 and 2 as they are no longer needed
c=or(index_a,index_b); % logical row index
c=[c;c;c]; % logic array to delete values as required
data_trunc(c)=[];
Running the following code shows the difference in speed:
data = randi([1 100],10000,1);
tic
for ii=1:10000
data_trunc=reshape(data,[5,length(data)/5]); % convert to 5 by 2000 array
index_a=data_trunc(1,:)>48;
index_b=data_trunc(2,:)>48;
data_trunc(1:2,:)=[];
c=or(index_a,index_b);
c=[c;c;c];
data_trunc(c)=[];
end
toc
On my computer it took 0.778 seconds to run it 10000 times.
tic
for ii=1:10000
ind = ones(length(data),1);
for i = 1:5:length(data)
if (data(i) > 48 || data(i+1) > 48)
ind(i:i+4) = 0;
else
ind(i:i+1) = 0;
end
end
data_trunc = data(logical(ind));
end
toc
Whereas implementing same using your looped example takes 16.7 seconds.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by