MATLAB: How to change an if-condition in a loop by logical indexing to make the code faster

for looplogical indexingMATLABperformancespeedstructure

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

Best Answer

It is likely that
A(i,:) == B(j,:)
is not doing what you think it is, especially in the context of an if statement. You may want
isequal(A(i,:), B(j, :));
or
all(A(i,:) == B(j,:))
or maybe
any(A(i,:) == B(j,:))
Also, there is no reason to evaluate
C(i,1) ~= 1
inside the j loop. Depending on your data, this could save a significant portion of time or very little. You probably also want to use
&&
instead of
&
since the former shot circuits when possible saving a comparison.