Read in a txt file with integers and string

10 views (last 30 days)
I don't think this question is too hard but I've really been struggling getting matlab to import my text file so I hope you all are able to help me!
Below is an example of the first few lines of the file that I manually put into excel to better show the data. The headers are not in the text file but are a description of the data in the columns.
I've had trouble reading this in even when I only try and read in the data with the first 3 columns but the besides the basics, the second to last string (highlighted in the picture) is sometimes not present and I'm not sure how to handle that so it will just be blank or changed to a 0 when I import the data.
Any help you all could give me would be greatly appreciated!
Thank you!
  3 Comments
RichB
RichB on 9 Feb 2015
Thanks for the suggestion Stephen. I just uploaded a txt file with the data. I'm working to test the code you gave me but still having some problems so far. Thanks for your help so far!
RichB
RichB on 9 Feb 2015
Wow, okay. I think I figured out why it wasn't working initially. The text file I was working with was saved as UTF-8 vs ANSI. It all works great now.
Thank you!

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 9 Feb 2015
Edited: Stephen23 on 9 Feb 2015
textscan is your friend. If you upload a small text file of your data, I can show you how it can be configured to work with your data.
Given your image of the excel spreadsheet, I came up with this:
fid = fopen('temp.txt','rt');
C = textscan(fid,'%d%d%s%s%d%f%s%s%s','Delimiter','\t','Whitespace','');
fclose(fid);
This returns me a 1x9 size cell array with all of the file's data in it, for example:
>> C{6}
ans =
17.5000
17.5000
12.2500
8.5000
7.8750
>> C{9}
ans =
'HC606'
'HCM605'
'HCR408'
'DP0768'
'DP506Z'
The data file is attached. Feel free to use it to test this code with.
Note that if you have a newer version of MATLAB, you can also use tables , in which case readtable might do the job for you.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!