MATLAB: How to efficiently implement if statements looping over three matrices

nested loop and if statement

I have a matrix of size 4000×3 matrix [K]
I have to identify all possible triplets which are elements of K such that
K(i,:)+K(j,:)=K(k,:)
i.e. sum of two elements of K equals third element
Currently I'm using three loops and an if statement to do this:
k_tol= 1e-6;
for i1=1:size(K,1)
k1= K(i1,:);
for i2=1:size(K,1)
k2= K(i2,:);
for i3=1:size(K,1)
k3= K(i3,:);
if (norm(k1+k2-k3)<=k_tol)
ModeNp(counterNp,:)= [i3,i2,i1];
counterNp=counterNp+1;
end
end
end
end
The above code works fine, but is very slow. My actual K matrix has ~4000 elements, this makes the triple nested loop very time consuming.
Is there a better, faster way of doing this?
Thanks a lot!

Best Answer

This solution uses my ndSparse class (Download). It runs in about 6.5 minutes on my machine, but was not tested with a realistic K, so hard to be sure of anything.
K=rand(4000,3); %fake data
k_tol=1e-4;
K=single(K);
[mk,nk]=size(K);
M=40; %chunk size
N=mk/M; %num. of chunks
tmp=cell(1,1,N);
map=true;
for i=1:3
c=K(:,i);
m=c+c.';
d=reshape(c,1,1,M,[]);
for n=1:N
tmp{n}=ndSparse(abs(m-d(:,:,:,n))<k_tol,[mk,mk,M]);
end
map=map&cat(3,tmp{:});
end
[i,j,k]=ind2sub(size(map),find(map));