How to change an if-condition in a loop by logical indexing to make my code faster?
Show older comments
Hi,
I have got a serious performance problem with the Matlab-code below. It works but the "for"-loop - especially the "if"-condition - is really slow.
How can I rewrite the "if"-condition to make my code faster? Maybe the key is to form a logical index?
Thanks a lot!
My code: - "A.", "B.": structural arrays containing matrices - "C.": structural array containing vectors
for k=1:numel(fields_A)
A = A.(fields_A{k});
B = B.(fields_A{k});
C = C.(fields_A{k});
for i = 1:size(A,1)
for j = 1:size(A,1)
if (A(i,:) == B(j,:) & C(i,1) ~= 1), C(j,1)=1;
end
end
end
A(find(C(:,1)==1),:)=[];
A.(fields_A{k})= A;
end
Accepted Answer
More Answers (1)
Andrei Bobrov
on 11 Apr 2012
[EDIT]
try
fn = fieldnames(A);
for jj = 1:numel(fn)
n = fn{jj};
[a b] = ismember(A.(n),B.(n),'rows');
C.(n)(b(b ~= 0),1) = 1;
A.(n) = A.(n)(C.(n)(:,1)~=1,:);
end
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!