replace nan in a matrix with specific values

4 次查看(过去 30 天)
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 中查找有关 Migrate GUIDE Apps 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by