Vectorized index generation based on multiple conditions

5 views (last 30 days)
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 Comment
Turlough Hughes
Turlough Hughes on 2 Oct 2019
Edited: Turlough Hughes on 2 Oct 2019
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.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!