I have a table that looks like this
x x x x x x
x x
y y y y y y
y y
z z z z z z
z z
I want to import it using readtable
such that all the x are in one row, all the y in the next row, etc. In other words, in the .txt file the last two contents that are supposed to be in one line are shifted into the next. I think I need to change something in DelimitedTextImportOptions
but I cannot figure out what exactly.
Would be glad if someone could help me with this, thank you very much in advance!
If it is a requirement to use readtable, one option would be to transform the original file to a new format and then apply readtable to the new file.
Here are sample contents of the file in.txt
that can be used in the example below:
1 2 3 abc 5 6
7 8
3 4 5 def 7 8
9 0
9 1 0 ghi 3 2
1 4
Here is the code:
% FIRST, TRANSFORM THE INPUT FILE INTO A FILE WHERE THE SPLIT LINES ARE
% COMBINED INTO SINGLE LINES
% open input and output files
in = fopen('in.txt', 'r');
out = fopen('out.txt', 'w');
% read the first line of the input file
currline = fgetl(in);
% while we haven't reached the end of the file
while ~isequal(currline, -1)
% read the following line of the input file
currline_append = fgetl(in);
% ... if it doesn't exist, throw an error; the file is not as expected
if isequal(currline_append, -1)
error('Bad file');
end
% print this pair of lines to the output file as a single line.
% Note: if using Windows Notepad or similar application to read the
% file, you may want to replace '\n' by '\r\n' in the format string
fprintf(out, '%s %s\n', currline, currline_append);
% get the next line of the input file
currline = fgetl(in);
end
% close input and output files
fclose(in);
fclose(out);
% NEXT, READ THE TABLE FROM THE OUTPUT FILE
t = readtable('out.txt');