How to replace missing values in a cell array?
232 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
TADA
2019-7-24
x = {missing(), 1, 2, 3, missing(), missing(), 5};
mask = cellfun(@ismissing, x);
x(mask) = {[]}; % or whatever value you want to use
3 个评论
James Brown
2019-12-16
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.
更多回答(1 个)
Jesse Ivers
2022-7-20
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) = {[]}
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!