MATLAB: How do interpolate and hold values inside a vector

arraysexcelMATLAB Compilervectors

I have a vector that looks like this:
NA
NA
-33.20
-37.98
-40.83
-52.36
NA
-28.42
NA
NA
NA
-24.74
NA
NA
NA
-26.33
NA
NA
NA
-23.10
NA
NA
NA
-25.04
NA
NA
I am trying to build a function that can replace the NAs in the above vector using the following cases:
  • from the beginning, in which case I hold the first non NA value (-33.20 for the first two NAs here)
  • in the middle, where I interpolate because I have a start and stop value (between -52.36 and -28.42; between -28.42 and -24.72 and so on…)
  • towards the end, where I hold the last non NA value(-25.04 for the last two NAs)
I am relatively new to Matlab and this is what basic structure I have so far:
count = 0;
interp = 0;
hold = 0;
for cols = 1:34
for rows = 1:26
if (HMF(rows,cols)~=NA)
start=HMF(rows,cols);
end
if (HMF(rows,cols)==NA)
count = count + 1;
interp=1;
if(rows==1||rows==26)
hold=1;
interp=0;
end
end
stop = HMF(rows,cols);
if(interp == 1 && hold ==0)
%interpolate between start and stop
elseif (hold==1 && interp ==0)
%hold value of last known element
end
end
end

Best Answer

See if something like this is what you are looking for:
input = [nan; nan;-33.20; -37.98; -40.83;...
-52.36; nan; -28.42; nan; nan; nan;...
-24.74; nan; nan; nan; -26.33; nan;...
nan; nan; -23.10; nan; nan; nan; ...
-25.04; nan; nan];
% Intermediate step will interpolate to fill inner NaN's
intermediate = interp1(find(~isnan(input)),input(~isnan(input)),1:numel(input));
% Second interp will fill outer NaNs with the closest real value
output = interp1(find(~isnan(intermediate)),intermediate(~isnan(intermediate)),...
1:numel(intermediate),'nearest','extrap');
Essentially, the first interpolation is just linear and will fill in the NaNs that have values on either side. If you look at the output of this step, you will see that the NaNs remain on the edges.
The second interp1 call gets rid of the outer NaNs using the 'extrap' option, but also just fills them in with the nearest good value (which is what the 'nearest' option does)
This does make the assumption that your inputs are equally spaced. If that is not hte case, you would need to replace the first and last inputs into the interp1 function with something that describes the spacing of the data points.
Note: Edited output line to correct typo