How do you replace NaN values in column n with the average of the all the values in column n?

10 次查看(过去 30 天)
I have a 9172x27 matrix called ProjectData_E where there is a handful of missing data. I have found a way to find the average value for each column, n, while passing over the NaN values and that are stored in a 1x27 matrix called column_mean. I have tried playing around with the isnan function and creating a loop, but I am struggeling on how to replace NaN values in column 1 with the average of all the values of column 1 and so on. Is there another way to go about this?
for j = 1:27
ProjectData_E(isnan(ProjectData_E)) = column_mean(:,j);
end
I have tried playing around with a simple loop like this, but either it does not work at all or all NaN values are replaced with the mean of column 1.

回答(1 个)

David Hill
David Hill 2022-11-16
r=rand(9172,27);
r(randi(247644,1,10000))=nan;%add some nan's
m=mean(r,'omitnan');
[~,idx]=find(isnan(r));
r(isnan(r))=m(idx);

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by