indexing with isnan in multidimensional arrays
Show older comments
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 Comments
It's not clear what you're after. None of these are 2x1 or 1x1.
load lon_nonan_reshape_use; size(lon_nonan_reshape_use)
idx = ~isnan(lon_nonan_reshape_use); size(idx)
lon_nonan_adj = lon_nonan_reshape_use(idx); size(lon_nonan_adj)
ans(1)/2 % not the same number of elements as before because nans are missing
If you want lon_nonan_adj to be the same shape as lon_nonan_reshape_use, with the NaNs preserved, then there's no reason to have made it in the first place. You would have removed the NaNs and then put them back in the same spots. I don't get it.
Sagar Parajuli
on 12 Aug 2021
DGM
on 12 Aug 2021
"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
on 13 Aug 2021
Accepted Answer
More Answers (1)
% 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, :)
1 Comment
Sagar Parajuli
on 13 Aug 2021
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!