Logical indexing vs Linear indexing for arrays

8 Ansichten (letzte 30 Tage)
B H
B H am 24 Apr. 2017
Beantwortet: Star Strider am 24 Apr. 2017
I've been trying to speed up some code recently that uses logical indexing and found that using linear indexing is significantly faster for a particular isolated case. I've included an example of what I'm seeing.
data = ones(12000, 26000, 'double');
msk = false(size(data));
msk(1:4, :) = true;
t = tic;
data_out = data(1:4, :);
toc(t);
data2_out = zeros(4, size(data, 2));
t = tic;
data2_out(:) = data(msk);
toc(t);
data_out takes 0.004s vs 0.3s for data2_out. I can see that data_out is faster because there are less elements to index through. But I thought logical indexing would skip all the zeros. Is that not the case? Or am I doing something wrong here, is there a faster way to use logical indexing? Are there other recommendations to speed up array indexing?
I was hoping to get away with exclusively using logical indexing - but it's looking like I'll have to find a balance between linear and logical indexing. Is that expected?
I'm using MATLAB 2016b 64bit in case that matters.

Antworten (1)

Star Strider
Star Strider am 24 Apr. 2017
‘But I thought logical indexing would skip all the zeros. Is that not the case?’
It is not. The logical vector will be the same size as the vector that created it, so the code will iterate through every value.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by