필터 지우기
필터 지우기

Vectorizing for loop with with strcmp function inside

조회 수: 3 (최근 30일)
Avijit Chowdhury
Avijit Chowdhury 2019년 1월 11일
댓글: Avijit Chowdhury 2019년 1월 11일
Hi,
I have a very large cell array (A), which has 3 columns with 1066426 rows of data.
What I am trying to do is for each row (row ii), find the one and only row in A (say row j) for which A(j,1) is the same as A(ii,2), & A(j,2) is the same as A(ii,1). Then, get A(j,3) and put it into a structure list (dayne(ii).bsg). Below is my code:
Parfor ii =1:length(A)
dayne(ii).bsg=cell2mat(A((strcmp(A(:,2),A(ii,1)) & strcmp(A(:,1),A(ii,2))),3));
end
The code is working, but its taking a really long time (about 30 mins for 1% to be completed). I have already used parfor to utliize parallel workers.
Can anyone suggest if (and how) this code can be vectorized?
Is there any other way to make it work faster?
Thank you very much for the help.

답변 (1개)

Stephen23
Stephen23 2019년 1월 11일
편집: Stephen23 2019년 1월 11일
Reverse the loop order and get rid of the cell2mat:
for ii = numel(A):-1:1
idx = strcmp(A(:,2),A(ii,1)) & strcmp(A(:,1),A(ii,2));
dayne(ii).bsg = A{idx,3};
end
  댓글 수: 1
Avijit Chowdhury
Avijit Chowdhury 2019년 1월 11일
Thanks for the help, it seems to be somewhat faster. However, I am not able to use parfor, and since there maybe iterations where the outpull is null (does not meet the criteria), I have had to add in some more commands:
I have timed it and seems to be taking 14sec/100 iterations.
for ii= length(A):-1:1
idx = strcmp(A(:,2),A(ii,1)) & strcmp(A(:,1),A(ii,2));
if any(idx)
dayne(ii).bsg = A{idx,3};
else
end
end

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by