필터 지우기
필터 지우기

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

조회 수: 2 (최근 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
Stephen23 2022년 3월 28일
Do NOT name your variable mean, because that is the name of a very important inbuilt function.
Mathieu NOE
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
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?
  댓글 수: 1
Aafke  Kerkhof
Aafke Kerkhof 2022년 3월 29일
Because I am completely new to MATLAB and I thought that would be the only possibility, but this worked like a charm thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Bjorn Gustavsson
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

Mathieu NOE
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

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by