Understanding the Syntax for deleting rows with NaN

1 vue (au cours des 30 derniers jours)
aldburg
aldburg le 19 Fév 2018
Commenté : aldburg le 19 Fév 2018
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.

Réponse acceptée

Walter Roberson
Walter Roberson le 19 Fév 2018
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.
  1 commentaire
aldburg
aldburg le 19 Fév 2018
Thank you for the response. I only understood half, just a beginner at coding, but it already helped a lot.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by