sample and hold kind of interpolation

Hi,
Say x =
[1 12 NaN;
2 NaN 6;
3 13 NaN;
4 NaN 7;
5 15 NaN;
7 17 NaN;
11 19 NaN;
12 NaN 9]
Without using loops, how can I replace NaNs with the previous values in each column, so that I have
x =
[1 12 0;
2 12 6;
3 13 6;
4 13 7;
5 15 7;
7 17 7;
11 19 7;
12 19 9]
Thanks a lot in advance,
axs

1 Comment

It's a bit tricky without any for loop at all, but start with isnan()

Sign in to comment.

 Accepted Answer

t = [true(1,size(x,2));~isnan(x)];
x1 = [ones(1,size(x,2));x]
x2 = x1(~isnan(x1))
x1(:) = x2(cumsum(t(:)))
out = x1(2:end,:)
out(1,isnan(x(1,:))) = 0
use loop for...end
x(1,isnan(x(1,:))) = 0;
for i1 = 2:size(x,1)
t = isnan(x(i1,:));
x(i1,t) = x(i1-1,t);
end

3 Comments

I tried the first part without the loop and it works perfectly fine. Thanks a lot for the help.
I had just given some dummy data over there. The actual data I want to use this is on multiple sensor information. The first column is the time axis, second column is from one sensor and the third from another sensor. Both the sensors work at different frequencies and have their own timestamps. I wanted to consolidate all information into one matrix with a common timestamp initially. I didnt want to interpolate the data between points as thats not how it really works. It holds on to the data till there is a new information.
for loop would have been very expensive in terms of time, so wanted a better approach.
Honestly I did not understand how these lines worked, and would like to know it.
x2 = x1(~isnan(x1))
x1(:) = x2(cumsum(t(:)))
Other than that I really liked the short and quick approach.
Thanks once again,
axs
x2 = where are there not nans in x1?
x1 = x2 of the indices of where x2 already isn';t nans and the next few values.
Break it into pieces to visualize what is happening.
Thanks, got it.

Sign in to comment.

More Answers (0)

Categories

Find more on Interpolation of 2-D Selections in 3-D Grids 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!