Dealing with NaNs in a code

조회 수: 3 (최근 30일)
Nicu Sprincean
Nicu Sprincean 2017년 4월 7일
댓글: Star Strider 2017년 4월 10일
Hi everyone, I'm struggling with a code that doesn't accept the NaNs. This is a part of a bigger code:
data = [y1 y2];
for i=1:5
c(:,i) = mean(data(:,i));
d(:,i)=(data(:,i));
data_demeaned(:,i) = d(:,i) - c(:,i);
end
I've tried to do this:
c(:,i) = nanmean(data(:,i));
d(:,i)= data(:,i)(~isnan(data(:,i)));/ d(:,i)=~isnan(data(:,i));
data_demeaned(:,i) = d(:,i) - c(:,i);
but it doesn't work. Any suggestion would be highly appreciated.

답변 (1개)

Star Strider
Star Strider 2017년 4월 7일
I believe you’re making this more difficult than it needs to be. I do not understand what you are doing with your ‘d’ matrix, since the code doesn’t make sense, so please explain it.
Try this:
data = rand(1,30); % Create Data
data(randperm(30,10)) = NaN; % Create Data (Insert ‘NaN’ Values)
data = reshape(data, [], 5); % Create Data
c = nanmean(data);
data_demeaned = data - c;
  댓글 수: 12
Nicu Sprincean
Nicu Sprincean 2017년 4월 10일
편집: Nicu Sprincean 2017년 4월 10일
Hi, again. I have another issue. I have a MxN matrix (matrix A) and I run the following code:
B = A(~isnan(A));
but I get a Mx1 vector as a result. How could I manage it to get a matrix, with the same number of columns (N)? Or this happens due to the fact that the number of rows is not equal? Thank you.
Star Strider
Star Strider 2017년 4월 10일
My pleasure.
That is normal, and results from numeric arrays not being defined to have ‘empty’ elements, so the matrix structure disappears and produces a vector of the ‘non-NaN’ values. (Cell arrays can have empty elements.)
You can create the original matrix as a cell array with the num2cell function. That will allow ‘empty’ elements, although it introduces the complexities of calculating with cell arrays, and does not eliminate your original problem.
That it has (Mx1) elements indicates to me that it has (M-1)*N elements that were NaN.
Since you have functions available that automatically calculate with NaN values and handle them as you want them to, I would just use those functions and not deal with eliminating the NaN values or using cell arrays.

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

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by