MATLAB Answers


Replace NaN with specific value.

Asked by Mehul Agrawal on 27 Jun 2016
Latest activity Commented on by Steven Lord
on 27 Jun 2016
I have many large column matrices (each is ~20k x 1). Some elements of the matrices are NaN. I want to replace them with 0 (or some number). Is there a quick way for that. Looping through each element is a very inefficient process and delays my program. The help is really appreciated.


Sign in to comment.

1 Answer

Answer by Guillaume
on 27 Jun 2016
Edited by Guillaume
on 27 Jun 2016
 Accepted Answer

yourmatrix(isnan(yourmatrix)) = somevalue;
But, using NaN to mark exceptional values is much better than using 0 or some other special value.


Thanks a lot. I actually wanted to do some additions of these matrices and having NaN ignores all other calculations and I will end up having NaN. For my purpose 0 is actually a unique value too (just eligible for calculations).
Steven Lord
on 27 Jun 2016
For a couple releases now the sum function has accepted a flag that lets you specify whether NaN values should be included in the sum (which makes the sum NaN) or excluded (unless all the values being summed are NaN.)

Sign in to comment.