indexing with isnan in multidimensional arrays
조회 수: 15 (최근 30일)
이전 댓글 표시
I have this code:
load lon_nonan_reshape_use;
idx = ~isnan(lon_nonan_reshape_use);
lon_nonan_adj = lon_nonan_reshape_use(idx);
In the above example, lon_nonan_reshape_use and idx both are of size n*2 so I expect lon_nonan_adj also to be of n*2. MATLAB gives the results in n*1 dimension because lon_nonan_adj(:, 1) is not equal to lon_nonan_adj(:, 2) which is sensible. But I still want to get lon_nonan_adj as a n*2 matrix with NaNs retained in the place where there were NaNs previously. Could you please help?
댓글 수: 4
DGM
2021년 8월 12일
"But I still want to get lon_nonan_adj as a n*2 matrix with NaNs retained in the place where there were NaNs previously."
If you take matrix A, remove all the NaNs and then fill all the empty spots left over with NaN such that the size is preserved, then you're back at A. I don't see how the operation isn't superfluous.
채택된 답변
Walter Roberson
2021년 8월 12일
load lon_nonan_reshape_use;
idx = ~all(isnan(lon_nonan_reshape_use),2);
lon_nonan_adj = lon_nonan_reshape_use(idx,:);
This retains rows provided there is at least one non-nan in the row.
댓글 수: 1
Walter Roberson
2021년 8월 13일
If you want to remove all rows with NaN anywhere in the row, then
rmmissing(lon_nonan_reshape_use)
추가 답변 (1개)
Chunru
2021년 8월 12일
% A small matrix with nans
a=randn(6, 3);
a([2 11 13])=nan
% idx
idx = ~isnan(a)
a(idx)
So a(idx) is a colum matrix based on the original a by removing all nans and arranged in a column vector.
If you want to remove all rows with nans (it looks so for your problem), then you can do the following
idx1 = all(~isnan(a), 2)
a(idx1, :)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!