Vectorized index generation based on multiple conditions
2 次查看(过去 30 天)
显示 更早的评论
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
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!