How to exclude/extract empty rows/columns in a table?
조회 수: 55 (최근 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!