Understanding the Syntax for deleting rows with NaN
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Walter Roberson
2018년 2월 19일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!