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
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.
Sagar Parajuli
Sagar Parajuli 2021-8-13
I think you are right, so it looks like I should get rid of all NaNs and deal with the no-nan data only as answered below. Thank you.

请先登录,再进行评论。

采纳的回答

Walter Roberson
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 个)

Chunru
Chunru 2021-8-12
% A small matrix with nans
a=randn(6, 3);
a([2 11 13])=nan
a = 6×3
-0.5340 0.4891 NaN NaN 0.2906 0.4462 -1.2660 -1.1701 2.0372 -0.3616 -0.4775 0.3251 0.6966 NaN 0.1013 0.4787 1.2229 -0.6159
% idx
idx = ~isnan(a)
idx = 6×3 logical array
1 1 0 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1
a(idx)
ans = 15×1
-0.5340 -1.2660 -0.3616 0.6966 0.4787 0.4891 0.2906 -1.1701 -0.4775 1.2229
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)
idx1 = 6×1 logical array
0 0 1 1 0 1
a(idx1, :)
ans = 3×3
-1.2660 -1.1701 2.0372 -0.3616 -0.4775 0.3251 0.4787 1.2229 -0.6159
  1 个评论
Sagar Parajuli
Sagar Parajuli 2021-8-13
I like your last solution because ultimately that is what I need (data with all NaNs removed), to input to 'griddata'. Thank you for forseeing my problem.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by