Replacing nans and greater than
Show older comments
I have a file with 3 columns. I need to change all the NaNs in the second column of the cell array to empty cells, and the corresponding row in column 3 with number 4. I also need to do the same for numbers greater than 0.2, changing row 3 to a 5.
I tried something like this:
if database(:,2) = is a nan then it will change to []
database(:,3) = 4
if database(:,2) > 0.2
database(:,3) = 5
1 Comment
James Tursa
on 24 May 2015
What do you get when you type:
whos database
Accepted Answer
More Answers (1)
Walter Roberson
on 24 May 2015
nanpos = cellfun(@(C) any(isnan(C)), database(:,2));
database(nanpos,2) = {};
database(nanpos,3) = {4};
pos02 = cellfun(@(C) any(C>0.2), database(:,2));
database(pos02,3) = {5};
You need to decide whether database is a numeric array or a cell array. If it is a numeric array then you cannot put in empty cells: every entry in a numeric array must be a (possibly NaN) numeric entry. If the database is a cell array, then you cannot put a number in a column: you have to put a cell containing the number.
For the 0.2 condition, notice that I used any(C>0.2) and not C>0.2 directly. We just changed some of the entries to the empty cell a moment before, so we don't know how many numbers there are in the given cell. There might be 0, there might be 1, there might be... well, you didn't define: if you are working with a numeric array then of course there is only one entry but then you would not be able to replace the entries with emptiness. So to make the question work we have to assume that each entry is a cell, and when we do that, it is no longer safe to assume that each cell will be either empty or a scalar. Even if you can guarantee that to be the case, cells of empty array or scalars, then if you use just C>0.2 then if C is empty then []>0.2 is defined as [], but you can't return the [] without changing to 'Uniform', 0, and then you would have to post-process the resulting cells. Easier all around to use any() as that is well defined for empty vectors.
2 Comments
Nicole Scerri
on 24 May 2015
Edited: Nicole Scerri
on 24 May 2015
Walter Roberson
on 24 May 2015
When you say it is a table, do you mean that it was created with table() ? If so then see http://www.mathworks.com/help/matlab/matlab_prog/clean-messy-and-missing-data-in-tables.html
Categories
Find more on Data Type Conversion 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!