Vectorizing for loop with with strcmp function inside

1 次查看(过去 30 天)
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