Filter löschen
Filter löschen

Vectorizing for loop with with strcmp function inside

1 Ansicht (letzte 30 Tage)
Avijit Chowdhury
Avijit Chowdhury am 11 Jan. 2019
Kommentiert: Avijit Chowdhury am 11 Jan. 2019
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.

Antworten (1)

Stephen23
Stephen23 am 11 Jan. 2019
Bearbeitet: Stephen23 am 11 Jan. 2019
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 Kommentar
Avijit Chowdhury
Avijit Chowdhury am 11 Jan. 2019
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by