MATLAB: Fill NAN values in a table

interpolation

Hi,
I have a table that consists of 5 columns
One column, temperature, displays some NAN values
I would like to use the inpaint_nans function to fill the NAN by interpolation
How do I fill in the temperature column only?
Then save the table as new table after NAN filled?
Thank you.

Best Answer

Try this well commented example I created for you:
% Create data because the user forgot to post any!
% Make random values for Date, temp, humidity, pressure, precip, depth
numRows = 50;
temperature = randi(100, [numRows, 1]);
humidity = randi(100, [numRows, 1]);
pressure = randi(100, [numRows, 1]);
precip = randi(100, [numRows, 1]);
depth = randi(100, [numRows, 1]);
% Make some of the temperature elements nan
temperature(10:20) = nan;
indexes = randperm(length(temperature), 8); % 8 other random locations.
temperature(indexes) = nan;
% Create a table, T, as a container for the workspace variables.
T = table(temperature, humidity, pressure, precip, depth)
%------------------------------------------------------------------------
% % Now we have our table and we can begin.
% Now fix the nans. First extract the temperature column.
temperature = T.temperature
% Find nan locations (rows)
nanRows = isnan(temperature)
% Sometimes, either the first or last element(s) are nan, and the interpolation will leave a nan there.
% So to prevent that we have to find the first non-nan element and tack it onto the beginning,
% and find the last non-nan element and tack it on to the end.
indexes = find(~nanRows)
repairedTemperature = [temperature(indexes(1)); temperature; temperature(indexes(end))]; % Make sure to use semicolon rather than comma.
% Find nan locations (rows) again with the "fixed" array.
nanRows = isnan(repairedTemperature)
% Interpolate non-nan locations
repairedTemperature = interp1(find(~nanRows), repairedTemperature(~nanRows), 1:length(repairedTemperature))
% Now truncate off the first and last elements we tacked on. Also need to transpose since interp1() gives a row vector.
repairedTemperature = repairedTemperature(2:end-1)';
% Stick the results back into the table.
T.temperature = repairedTemperature;
fprintf('All done with demo by Image Analyst.\n');