필터 지우기
필터 지우기

replace nan in a matrix with specific values

조회 수: 1 (최근 30일)
Hajar Alshaikh
Hajar Alshaikh 2022년 11월 15일
댓글: Hajar Alshaikh 2022년 11월 15일
I do not know why the following code does not work
I have a matrix F which has some of nan entries, and i have saved the last row of this matrix as N_lastrow. then I want to replace all nan entries in this row such that if F is 4*4 matrix and if N_lastrow(4,4)= nan , then replace it directly by the mean of the whole rest of entries in F. However, any other nan values such that if N_lastrow(1,2)=nan, we have to replace it by the value of of F(3,3) and if it is also nan I will replace it by F(2,4), and if it is also nan then replace it by the mean of the whole rest of entries.
THIS IS THE CODE
f;
N_lastrow=f(n,:);% where n is the number of rows in f
for k=1:n
if isnan(N_lastrow(1,k))
if k==n
N_lastrow(1,k)=nanmean(f,'all')
break
end
for m=n:1
if m-1 >0
N_lastrow(1,k)=f(m-1,k+1)
if ~isnan(f(m-1,k+1))
break
end
else
N_lastrow(1,k)=nanmean(f,'all')
end
end
else
N_lastrow(1,k)=f(n,k)
end
end
N_lastrow

답변 (1개)

Kevin Holly
Kevin Holly 2022년 11월 15일
Can you give clarity to what you want? To me, it sounds like you want something like this:
f = [1 2 3 2; 4 5 6 1; 7 8 9 2];
f(4,4) = NaN
f = 4×4
1 2 3 2 4 5 6 1 7 8 9 2 0 0 0 NaN
N_lastrow=f(end,:)
N_lastrow = 1×4
0 0 0 NaN
if isnan(f(4,4))
f(4,4) = f(3,3);
if isnan(f(3,3))
f(4,4) = f(2,4);
if isnan(f(4,4))
f(4,4) = mean(f,'omitnan');
end
end
end
f
f = 4×4
1 2 3 2 4 5 6 1 7 8 9 2 0 0 0 9
N_lastrow=f(end,:)
N_lastrow = 1×4
0 0 0 9
  댓글 수: 1
Hajar Alshaikh
Hajar Alshaikh 2022년 11월 15일
no. if N_lastrow(1,n) is nan then direct f(n,n) = mean(f,'omitnan');
so f(4,4)=f(3,3) is not right
please review the code that I wrote up
my question is why nan still appear after i run my code?

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

카테고리

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

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by