필터 지우기
필터 지우기

Understanding the Syntax for deleting rows with NaN

조회 수: 2 (최근 30일)
aldburg
aldburg 2018년 2월 19일
댓글: aldburg 2018년 2월 19일
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.

채택된 답변

Walter Roberson
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.
  댓글 수: 1
aldburg
aldburg 2018년 2월 19일
Thank you for the response. I only understood half, just a beginner at coding, but it already helped a lot.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by