10 views (last 30 days)

Hi I have a 300x200 matrix with numbers ranging from 0 to 3. I also have NaN interspersed within the matrix like

[2 1 1 1 1 1 1 2 2 2 2 2;

2 2 3 3 3 N 2 3 3 3 0 0;

2 2 0 N 1 2 1 N 1 1 2 3;] NaN represented as N

is there a way to use logical indexing to replace the elements NaN to the number that precedes it? and perhaps to replace Nan with the element that occurs in the highest frequency out of the preceding 3 elements? Thank you!

I can use if and for loop but would prefer to keep the time short in favour of speed. Any use if I could use isnan to create the matrix to identify NaN first?

Jos (10584)
on 28 Feb 2017

To replace NaNs by the preceding value in the row, assuming no NaN's in the first column:

A = [ 2 1 1 1 1 1 1 2 2 2 2 2

2 2 3 3 111 NaN 2 3 3 3 0 0

2 2 222 NaN 1 2 333 NaN 1 1 2 3]

S2Ifun =@(x,y) sub2ind(size(A), x, y) % an anonymous helper function

[r,c] = find(isnan(A)) % where are the NanN's

A(S2Ifun(r,c)) = A(S2Ifun(r,c-1))

Chris Turnes
on 1 Mar 2017

Jos (10584)
on 2 Mar 2017

If you can replace the NaNs with a zeros, you can use my function FILLZERO. If there are zeros in your matrix you can replace them first with a novel value, and later replace them as well.

NovelValue = max(A(:)) + 1 % find a value not in A

A(A==0) = NovelValue % replace zeros

A(isnan(A)) = 0

A = fillzero(A,2)

A(A==NovelValue) = 0 % restore zeros

You can find my FILLZERO function here:

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/327289-how-to-replace-a-nan-element-with-an-preceeding-element-in-a-matrix-using-logical-indexing#comment_432716

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/327289-how-to-replace-a-nan-element-with-an-preceeding-element-in-a-matrix-using-logical-indexing#comment_432716

Sign in to comment.