How to remove corresponding rows of a second array in the case of NaNs in the first array?
1 次查看(过去 30 天)
显示 更早的评论
I have a double array called mean with e.g. 11 rows and 121 columns, where row 3, 6, and 7 are NaNs. I want to remove these NaNs, and also remove the corresponding rows of another array called clst.
I tried to remove the NaNs with the following code:
mean(all(isnan(mean),2),:) = [];
But i would like to create a for loop where for each row of 'mean' it would detect the NaNs, and remove these rows and the corresponding rows of 'clst'. Would someone be able to help me?
2 个评论
Stephen23
2022-3-28
Do NOT name your variable mean, because that is the name of a very important inbuilt function.
Mathieu NOE
2022-3-28
hi
it's not good pratice to give matlab native function names to variables
here we don't know by sure if mean is your variable or the matlab mean function
quite confusing
采纳的回答
Stephen23
2022-3-28
Where M is your matrix (do not use the name mean):
idx = all(isnan(M),2);
M(idx,:) = [];
clst(idx,:) = [];
Why do you want to use a loop?
更多回答(2 个)
Bjorn Gustavsson
2022-3-28
Something like this might be preferable to a straightforward loop:
x1 = randn(5,11);
x2 = x1;
x1(x1>1.5) = nan;
idxNaN = any(isnan(x1),2); % Or if you have entire rows with nans, then use all
x2(idxNaN,:) = [];
x1(idxNaN,:) = []; % or whatever "saving-operation" you want to do on those rows
Also worth repeating (even though it is nagging and grating): avoid using variable-names like mean that shadows the built-in commands, nothing but problems will come out of that. Instead use something more descriptive, like x_avg or x_mean. Then you instantly also see what you have the mean of.
HTH
0 个评论
Mathieu NOE
2022-3-28
hello again
a for loop is maybe overkill , but as it's what your are asking for , this is my suggestion :
i prefered the names A and B for your corresponding mean (ugh!) and clst arrays
% dummy data
A = rand(11,121);
A([3;6;7],:) = NaN;
B= rand(11,12);
B([3;6;7],:) = NaN;
% main code
[m,n] = size(A);
k = 0;
A2 = [];
B2 = [];
for ci = 1:m
tmp = A(ci,:);
if ~any(isnan(tmp))
k = k +1;
A2(k,:) = tmp;
B2(k,:) = B(ci,:);
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!