MATLAB: How to break from the following for loop when beta( J+1) become zero

breakforinfinite loop

for j=2:inf
w = A*V(:,j) - beta(j)*V(:,j-1);
alpha(j) = w'*V(:,j);
w = w - alpha(j)*V(:,j);
beta(j+1) = norm(w,2);
V(:,j+1) = w/beta(j+1);
loopcnt = loopcnt + 1;
end

Best Answer

Put this inside your loop:
if beta(j+1) == 0
break
end
You might not want to check for exact equality, because of possible floating point error. Instead, you could check like this
if abs(beta(j+1)) < 1.e-8
break
end
or use some other suitably small tolerance.