How to replace missing values in a cell array?
222 views (last 30 days)
Show older comments
When I use readcell() to import a .xlsx file, any empty cells are stored as 1x1 missing. Then if I try to write the cell array back to a .csv file using writecell(), I get an error that missing values aren't allowed. It seems strange to me that readcell() would create something that writecell() can't handle, but given this limitation, how can I automatically detect all cells in my cell array that are missing and replace them with an empty string? I tried ismissing() and fillmissing() but these didn't work.
r = readcell('myinput.xlsx')
% r =
%
% 3×3 cell array
%
% {'a'} {'b' } {'c' }
% {[1]} {[ 3]} {1×1 missing}
% {[2]} {1×1 missing} {[ 6]}
writecell(r, 'myoutput.csv')
% Error using writecell (line 119)
% Unsupported cell element of type 'missing'. Convert the element
% to numeric, logical string, datetime, duration or categorical
% before writing.
ismissing(r)
% Error using matlab.internal.math.ismissingKernel/arraySwitch
% (line 79)
% First argument must be numeric, logical, datetime, duration,
% calendarDuration, string, categorical, char, cellstr, table, or
% timetable.
%
% Error in matlab.internal.math.ismissingKernel (line 16)
% IA = arraySwitch(A,false);
%
% Error in ismissing (line 70)
% IA = matlab.internal.math.ismissingKernel(A);
fillmissing(r, 'constant', '')
% Error using fillmissing/parseInputs (line 373)
% First argument must be numeric, logical, datetime, duration,
% calendarDuration, string, categorical, char, cellstr, table, or
% timetable.
%
% Error in fillmissing (line 127)
% [A,AisTable,intM,intConstOrWinSize,extM,x,dim,dataVars,ma] =
% parseInputs(A,fillMethod,varargin{:});
0 Comments
Accepted Answer
TADA
on 24 Jul 2019
x = {missing(), 1, 2, 3, missing(), missing(), 5};
mask = cellfun(@ismissing, x);
x(mask) = {[]}; % or whatever value you want to use
3 Comments
James Brown
on 16 Dec 2019
Slightly differrent scenario, but works great for me too. Exactly like a mask, but I'm not sure why MATLAB recognizes "mask" as a mask rather than a vector of zero or one indicies.
More Answers (1)
Jesse Ivers
on 20 Jul 2022
I needed some categorical data in my output table, which required a slightly different solution, because the cells with strings were outputtinga logical array, rather than a single value for missing. In case anyone else is in the same boat, here is what I found:
C = {'names', 'category', 'category with spaces', missing(); 'values', 3, missing(), 5};
mask = cellfun(@(x) any(isa(x,'missing')), C); % using isa instead of ismissing allows white space through
C(mask) = {[]}
See Also
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!