replace nan in a matrix with specific values
4 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Kevin Holly
on 15 Nov 2022
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
N_lastrow=f(end,:)
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
N_lastrow=f(end,:)
See Also
Categories
Find more on Migrate GUIDE Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!