필터 지우기
필터 지우기

replace missing values in a matrix

조회 수: 2 (최근 30일)
Richard
Richard 2012년 11월 20일
Consider the following:
A = [1,1,1;
2,3,1;
nan,3,1;
nan,3,nan];
how would I replace the missing values with the previous values? For example:
data =
1 1 1
2 3 1
2 3 1
2 3 1
I can find the nan by isnan(data) but I don't know how to replace the values as described.
Amended:
I've managed to do this but not in a very concise way:
A = [1,1,1;2,3,1;nan,3,1;nan,3,nan];
B = ~isnan(A);
I = arrayfun(@(x)find(B(:,x),1,'last'),1:size(A,2));
for i = 1:size(A,2);
C = A(:,i);
D = isnan(C);
C(D) = C(I(i));
Final(:,i) = C;
end
Could anyone suggest on a way to tidy this up?
  댓글 수: 1
Jan
Jan 2012년 11월 20일
Is this matrix a possible input:
A = [1, NaN; ... % NaNs in first row
NaN, 2; ... % Non-NaNs after a NaN
3, NaN]

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

채택된 답변

Jan
Jan 2012년 11월 20일
편집: Jan 2012년 11월 20일
What about a simple loop:
  • Go through the rows from 2 to end
  • Use isnan() to find the indices of NaNs
  • Replace values in the current row by the ones of the former row.
I'm not more specific, because this could be a homework also.
[EDITED]
for k = 2:size(A, 1)
index = isnan(A(k, :));
A(k, index) = A(k - 1, index);
end
  댓글 수: 2
Richard
Richard 2012년 11월 20일
not homework, just needed some advice...
Image Analyst
Image Analyst 2012년 11월 20일
But you didn't say whether you solved it or not. If you did, mark this as "Answered" otherwise show your code and where you're having difficulty.

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

추가 답변 (1개)

Matt J
Matt J 2012년 11월 20일
The FEX has this file
as well as many variants linked to it.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by