0
votes

I have a matrix with Col1 IDs and Col2 Values.

mat = [ ...
      1000 3
      1000 4
      1000 nan
      1000 nan
      1000 5

      2222 1
      2222 2
      2222 nan

      3333 nan

      4444 1 ] ;

I need to replace nan with the value in the row above it, but subject to the condition: row above should have the same ID.

Answer:

mat = [ ...
      1000 3
      1000 4
      1000 4
      1000 4
      1000 5

      2222 1
      2222 2
      2222 2

      3333 nan

      4444 1 ] ;

Can you suggest a vectorized approach?

1
I don't think this problem vectorizes well because of the need to find the first non-NaN value if there are consecutive NaNs with the same ID. - stardt
Simple loops are very fast with Matlab's JIT. Does a loop not meet your needs? - Rich C

1 Answers

4
votes

This code won't handle consecutive NaNs with the same ID.

inds = find([mat(2:end,1)==mat(1:end-1,1)] & isnan(mat(2:end,2)))
mat(inds+1,2) = mat(inds,2)

Running it twice on the sample data completes the task.