Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
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 comentarios
Stephen23
Stephen23 el 28 de Mzo. de 2022
Do NOT name your variable mean, because that is the name of a very important inbuilt function.
Mathieu NOE
Mathieu NOE el 28 de Mzo. de 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

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 28 de Mzo. de 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?
  1 comentario
Aafke  Kerkhof
Aafke Kerkhof el 29 de Mzo. de 2022
Because I am completely new to MATLAB and I thought that would be the only possibility, but this worked like a charm thanks!

Iniciar sesión para comentar.

Más respuestas (2)

Bjorn Gustavsson
Bjorn Gustavsson el 28 de Mzo. de 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 el 28 de Mzo. de 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

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by