How to exclude/extract empty rows/columns in a table?
57 次查看(过去 30 天)
显示 更早的评论
Hello,
I have a question about a code. I have a table with 8 columns (I use readtable command). In this file there are scattered blanks from column 5 to 8, and from column 1 to column 4.
I would like two files to be created from this file. one containing the filled (without blanks) columns 1 through 4, and the other file containing the filled without blanks columns 5 through 8.
I attach both the input (test_file.txt) and the two outputs (output1.txt & output2.txt) that I would like to have.
Could you please help me?
0 个评论
回答(2 个)
KSSV
2023-2-8
编辑:KSSV
2023-2-8
T = readtable('https://in.mathworks.com/matlabcentral/answers/uploaded_files/1288860/test_file.txt');
% Remove empty rows
idx = cellfun(@isempty,T.(1)) ;
T(idx,:) = [] ;
%
idx = isnan(T.(6)) ;
M = (1:height(T))' ;
idr = diff(find([1;diff(idx);1]));
D = mat2cell(M,idr(:),size(M,2)) ;
iwant = cell(length(D),1) ;
for i = 1:length(D)
iwant{i} = T(D{i},:) ;
end
Voss
2023-2-16
% read input file into table T
T = readtable('test_file.txt');
% get a logical matrix saying whether each element of the table is missing
% (NaN for numerics, '' for cell arrays of chars)
ism = ismissing(T);
% only output rows that have some missing value
rows_to_use = any(ism,2);
% rows without any missing value in the first 4 columns will go to output1
rows_for_output1 = ~any(ism(:,1:4),2);
% create two new tables from the original
output1 = T(rows_to_use & rows_for_output1,:);
output2 = T(rows_to_use & ~rows_for_output1,:);
% write the tables to their respective output files
writetable(output1,'output1.txt','Delimiter','\t','WriteVariableNames',false)
writetable(output2,'output2.txt','Delimiter','\t','WriteVariableNames',false)
% check the output files
type output1.txt
type output2.txt
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!