How to exclude/extract empty rows/columns in a table?
59 views (last 30 days)
Show older comments
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 Comments
Answers (2)
KSSV
on 8 Feb 2023
Edited: KSSV
on 8 Feb 2023
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
8 Comments
Voss
on 16 Feb 2023
% 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 Comments
See Also
Categories
Find more on Data Import and Analysis 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!