How to replace missing values in a cell array?
조회 수: 225 (최근 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) = {[]}
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!