Search code examples
matlabcell

MATLAB: Replace missing cell entries without replacing whitespaces


I'm reading an excel file using readcell, and all empty cells are imported as 'missing'. I would like to replace the missing, and i found the following suggestions (cellfun+anonymous function)

https://www.mathworks.com/matlabcentral/answers/473295-how-to-replace-missing-values-in-a-cell-array https://www.mathworks.com/matlabcentral/answers/464998-readcell-is-filling-cell-locations-with-1x1-missing

However, this solution also marks whitespaces as missing and replaces them

A = {1, 'test123', 2, 1, 'texthere';2, 'test456',  3 ,4, missing;...
    3, 'test789', missing, 1, 'text with spaces'}

A(cellfun(@(x) any(ismissing(x)), A)) = {'REPLACED'}

In this example, I would like 'text with spaces' to be left alone, and only to replace the actual 'missing' cells. How do I achieve this? Using 2019b.

Thanks!


Solution

  • The problem has to do with the any call around ismissing.

    As an alternative for ismissing You can use isa to explicitely test for the missing data class:

    >> A = {1, 'test123', 2, 1, 'texthere';2, 'test456',  3 ,4, missing;...
        3, 'test789', missing, 1, 'text with spaces'}
    >> A(cellfun(@(x) isa(x,'missing'), A)) = {'REPLACED'}
    A =
      3×5 cell array
        {[1]}    {'test123'}    {[       2]}    {[1]}    {'texthere'        }
        {[2]}    {'test456'}    {[       3]}    {[4]}    {'REPLACED'        }
        {[3]}    {'test789'}    {'REPLACED'}    {[1]}    {'text with spaces'}