Clear Filters
Clear Filters

How to remove corresponding rows of a second array in the case of NaNs in the first array?

2 views (last 30 days)
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 Comments
Mathieu NOE
Mathieu NOE on 28 Mar 2022
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

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 28 Mar 2022
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?

More Answers (2)

Bjorn Gustavsson
Bjorn Gustavsson on 28 Mar 2022
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

Mathieu NOE
Mathieu NOE on 28 Mar 2022
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

Tags

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!