MATLAB: When taking cross product I end up with NaN. how can i fix this

nan

I wrote a bit of code that grabs 3 points on a randomly oriented platelet to create two lines so that i can calculate the normal vector to the platelet using cross product. the normal vectors I am getting do not seem right and some of them turn out to be NaN i was wondering if someone can help me fix this. thank you!
matrix = [(1:natom)',mol_tag,x,y,z];
mol_tag1 = matrix(:,2);
unique_mol_tags = unique(mol_tag1);
num_tags = length( unique_mol_tags );
mol_normals = zeros(num_tags,3);
for k = 1 : num_tags
three_idx = find(mol_tag1 == unique_mol_tags(k),3,'first');
coords = matrix(three_idx,3:5); % gets the first 3 coordinates from each mol_tag grouping
p1 = coords(1,:);
p2 = coords(2,:);
p3 = coords(3,:);
lin1 = [p2-p1]; %Creates 2 lines to form a plane
lin2 = [p3-p1];
u1 = cross(lin1,lin2); % calculate cross product to find normal vector of the plane
u = u1/norm(u1)
% u(isnan(u))=0; % setting the NaN two zero doesn't seem to work either
mol_normals(k , :) = u;
bqij = 0;
for i = 1:3
for j = 1:3
singleij(i,j) = u(i)*u(j);
end
end
bqij = bqij + singleij;
end
qij = (bqij-(1/3*(eye(3))))/(num_tags);

Best Answer

No. You cannot "fix" it, in the sense that you will always get something with a NaN, using the code you have on the data you have. YOU might be able to fix the problem, in the sense that you can change your code to avoid the problem. For example, are you randomly sometimes selecting the same point twice in your selection?
NaNs result from several operations. For example, what is the result of inf-inf? Is it zero? Is it inf?
Likewise, what is 0/0? Again, it can arguably be ANY number, anything from 0 to 1 to 42 to inf, depending on how you take a limit.
How about inf/inf? Is it 1? 0? inf?
inf - inf
ans =
NaN
inf/inf
ans =
NaN
0/0
ans =
NaN
So your data has something in it that probably creates some infs (and therefore) some NaNs in it. Or it has a 0/0 operation in it. I cannot possibly know what did it, because I don't have your data.
Learn to use the debugger. It can help to detect where the problem arises.
help dbstop
dbstop if naninf