Azzera filtri
Azzera filtri

Vectorizing for loop with with strcmp function inside

3 visualizzazioni (ultimi 30 giorni)
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.

Risposte (1)

Stephen23
Stephen23 il 11 Gen 2019
Modificato: Stephen23 il 11 Gen 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 Commento
Avijit Chowdhury
Avijit Chowdhury il 11 Gen 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

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by