MATLAB: Understanding the Syntax for deleting rows with NaN

logical indexingMATLABsyntax

X = rand(10, 10);
X(X < 0.1) = NaN;
disp(X);
X(any(isnan(X), 2), :) = [];
I am having a hard time understanding all the parts of the bottom line. I understand isnan() returns an array where any NaN returns a 1 and 0 else. But I am lost at how any() works even after reading the syntax page and playing with it in MATLAB. What is the 2 used for and is it necessary? Why not:
X(any(isnan(X)), :) = [];
Likewise, what the [ ] afterward implies in this context.

Best Answer

any(TwoDimensionalArray,2) is equivalent to
nrow = size(TwoDimensionalArray,1);
ncol = size(TwoDimensionalArray,2);
result = false(nrow, 1);
for J = 1 : nrow
any_in_row = false;
for K = 1 : ncol
if ~isnan(TwoDimensionalArray(J,K) && TwoDimensionalArray(J,K) ~= 0
any_in_row = true;
break;
end
end
result(J) = any_in_row;
end
Which can also be written as
nrow = size(TwoDimensionalArray,1);
result = false(nrow, 1);
for J = 1 : nrow
result(J) = any(TwoDimensionalArray(J, :));
end
Without the ,2 the logic would be
ncol = size(TwoDimensionalArray,2);
result = false(1, ncol);
for J = 1 : ncol
result(J) = any(TwoDimensionalArray(:, J));
end
The dimension number such as 2 tells you which dimension is being "summarized" down to a single value.
So with the ,2 what you get out is a column vector of true and false values that tells you whether any of the values in that row were nan. And then you use that column vector of true and false values as a logical selector over rows; with the : for the second index, that selects all elements of the rows for which that was true. And then the = [] part is MATLAB syntax for deletion.