Give an example of a line where you're writing data that is nan. All I see is the first part where you write the string data but I don't know how you want the numerical data. For example, let's say DATA = [1,2,nan, 4,5]. Do you want
or do you want
in the csv file? And why can't you just write it out a number at a time using isnan() and fprintf()? You don't have to use dlmwrite() you know.