Delimited Text File - Title Association

1 view (last 30 days)
Ben
Ben on 31 Oct 2014
Commented: Image Analyst on 31 Oct 2014
Hi All,
Im just trying to import some data from X-Plane 10 into Matlab and just need a bit of advice.
After importing all my variables via the import tool I get about matrixes ranging from about 2500*50 to 50000*150 which is fine. However i then need to assign each column of this matrix a title so I can make comparisons and use the information further in my code.
The only method I know of doing this is individually assigning each title via:
Title = Data(:,ColumnNumber)
As the titles are already in the .txt file is there any way of automating this process so that Title1 goes with Column1 ect?
Ive attached on of my smaller outputs so you can see the sort of amount of data I am having to deal with.
Appreciate any help

Answers (1)

Image Analyst
Image Analyst on 31 Oct 2014
Yes. If you have R2013b or later you can use a table:
t = readtable(filename);
The members/fields of t will be your column headers that are in the first row of the text file.
  4 Comments
Ben
Ben on 31 Oct 2014
It is already in a .txt file. Sorry thought I had attached the file. Should be attached to this now
Image Analyst
Image Analyst on 31 Oct 2014
You might be able to get by with specifying a delimiter of a vertical bar and a space, but the underlines at the beginning of the names are going to be a problem. As you know variable names can't start with a special character or a number. If you wanted to use read table, you'd have to write a short (maybe 10 lines or so) function to read in the file line by line and strip out vertical bars and underlines. You can use strrep(). Try this code:
%====================================================
% Preprocess the text file so we can read it in with readtable().
fInput = fopen('data.txt', 'rt');
fOut = fopen('temp.txt', 'wt');
str = fgetl(fInput);
% Get rid of bad characters from first line.
str(str==',') = [];
str(str=='_') = [];
lineCount = 1;
while ischar(str);
fprintf(1, 'Read line #%d\n', lineCount);
% Get rid of bad characters.
str(str==' ') = []; % Remove spaces
str = strrep(str, '|', ','); % Replace bar by comma.
% Write out good line to new file.
fprintf(fOut, '%s\n', str);
% Retrieve the next line.
str = fgetl(fInput);
lineCount = lineCount + 1;
end
fclose(fInput);
fclose(fOut);
%====================================================
% Now read the table from the temporary file.
t = readtable('temp.txt', 'delimiter', ',');
% Get rid of temporary file because we don't need it anymore.
delete('temp.txt');
Now the table should have all the names in the first line of the file.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!