Understanding the Syntax for deleting rows with NaN
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposta accettata
Walter Roberson
il 19 Feb 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!