Logical indexing vs Linear indexing for arrays
조회 수: 8 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
Star Strider
2017년 4월 24일
‘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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!