MATLAB Answers

Import text file with different column lengths

조회 수: 80(최근 30일)
Cory Powell
Cory Powell 12 May 2017
답변: Hossam Etman 10 Jan 2020
This is a two part question:
1. Is it possible to import data from a .txt file with varying column lengths?
2. With that, is it possible to create a plot to which the lengths of data entries are not the same?
Scenario: I have three different load vs deflection tests but I want them all on the same plot. Each specimen failed at different times creating the various column dimensions between them all. Each data set has been imported to a separate MatLab code, adjusted, then exported to an .xlsx file. I have then put them all into one .xlsx file and created a .txt file from that and am now attempting to import them all and plot them on one plot.
If more clarity is needed please let me know.
Thank you ahead of time, Cory


Walter Roberson
Walter Roberson 12 May 2017
It would be easier to process the .xlsx files, even if there were columns of different lengths in them.
Failing that, if there is a consistent delimiter between columns, then you can use textscan, perhaps together with TreatAsEmpty
If you have spaces between columns instead of using delimiters between columns, and the missing entries are implied by the vertical alignment, then it becomes more difficult to import. In such a case, sometimes the easiest approach is to read the file as a single string, split into rows as a cellstr, then char() the cellstr so you get a char array, and then extract fixed column widths from the char array, in order to be able to deduce that the blanks mean "no entry"

  댓글 수: 2

Cory Powell
Cory Powell 19 May 2017
Hey thanks Walter.
Sorry to bother, I was hoping that maybe you could show a quick example code. All the columns of the .xlsx are filled just end at different rows and the columns are 'back to back', if that helps at all. Or maybe even a different post that you can think of that has something along these lines. I've searched quite a bit for which is what led me to posting the above request.
Thank you again, Cory
Walter Roberson
Walter Roberson 19 May 2017
With R2013b or later, you can read the simple sample irregular xlsx I give here with
data = readtable('irregular_columns.xlsx','ReadVariableNames',false)
the result is a table() object that has nan for the missing entries.

댓글을 달려면 로그인하십시오.

Vincent Scalfani
Vincent Scalfani 14 Jul 2018
Hi, this worked for me. Data file is read as a string, then each line is split into cell rows.
% Import data
data = fileread('data.txt');
data = cellstr(data);
% split at newline character
data = cellfun(@(newline) strsplit(newline, '\n'), data, 'UniformOutput', false);
% reposition split values into individual cells
% horizontal concatenation
data = [data{:}];
% transpose
data = data';

  댓글 수: 0

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by