How can I speedup this for loop and ismember?

조회 수: 5 (최근 30일)
Omar Ali Muhammed
Omar Ali Muhammed 2021년 3월 3일
댓글: Omar Ali Muhammed 2021년 3월 5일
Due to the large size of the arrays, the following suffers from extremly slow execution. Is it possible to speedup this code. Vout need to be modified by Vin according to specific locations pointed to by indx1 and indx2. In order to retrieve back the values of Vin from Vout, modification need to be down sequentialy starting from 1 to L Where some of these indices are distributed randomly between indx1 and indx2.
e=1; a=1; b=1; N=4;
L=262144; K=786432;
Vin=rand(1,L);
Vout=rand(1,K);
Q=randperm(K);
for r=Q,
if ismember(e,indx1)
Vout(r)=Vin(indx1(a));
a=a+1;
e=e+1;
elseif ismember(e,indx2)
Vout(r)=Vin(indx2(b));
b=b+1;
e=e+N;
else
Vout(r)=1;
e=e+N;
end
if e>L
break;
end
end
  댓글 수: 10
Paul Hoffrichter
Paul Hoffrichter 2021년 3월 5일
But in your example, K/L = 3. As I already mentioned, if, for example, length( indx1 ) = length( indx1 ) = K/2 - 1, this satisifies your requirement that size(indx1)+size(indx2) Less than K. In this case, the length of indx1 is larger than L. If all the values in indx1 is in the range of 1 to L, then there must be duplicates. But you said that indx1 has unique distinct and sorted vectors of indices.
The model you are presenting to us does not appear to be consistent for these reasons.
Omar Ali Muhammed
Omar Ali Muhammed 2021년 3월 5일
Dear I clearly stated that elements of indx1 and indx2 are in the range of 1 to L. So all indices of indx1 and indx2 not duplicated sorted and subset of K. e.g let us say K=100, then Vout has 100 elements, L=20, Vin has ten elements so indx1 may take values like 4, 7, 55, 89 and indx2 may take values like 1, 34, 67, 90, 97. Regards

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

채택된 답변

Jan
Jan 2021년 3월 4일
편집: Jan 2021년 3월 4일
Without having working inputs, we cannot run the function. Then it is not possible to improve the code reliably. Except for one detail: "e" is a scalar. Then ismember is an overkill. Faster:
if any(e == indx1)
If the elements of indx1 and indx2 are "small" integers, a lookup table can be faster:
LUT = zeros(1, L, 'uint8');
LUT(indx1) = 1;
LUT(indx2) = 2; % do indx1 and indx2 share elements?!
for r = Q
switch LUT(e)
case 0
Vout(r) = 1;
e = e + N;
case 1
Vout(r) = Vin(indx1(a));
a = a + 1;
e = e + 1;
case 2
Vout(r) = Vin(indx2(b));
b = b + 1;
e = e + N;
end
end
As said already, I cannot check if this is faster. Are indx1 and indx2 sorted? Are they unique integers?
I assume there is a vectorized approach also.

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by