read specific column of text file using Matlab

4 views (last 30 days)
Keqiao Li
Keqiao Li on 14 May 2015
Answered: Walter Roberson on 14 May 2015
My text file looks like the following text:
69.600000, 56.500000, 19991101, 0, 16.000000, 1, 5,3GGXC6,UCTP, 792,, 69.4139, 56.5321, 20725.632, 26267346, 7.33496,/Net/tholia/qscat/data/nc_test_daily/1999/, 935, 71
It is the first line of my text file. The rest of lines of the text file has same format I'm trying to read specific column of this text file by using Matlab, but it contains number and string.So How to get certain column of this text file? Need some help to solve this problem. Thanks

Answers (2)

Star Strider
Star Strider on 14 May 2015
If all the rows of your file are of the same format, the textscan function could probably read it. You would use the ‘format specification’ to choose the column to read.

Walter Roberson
Walter Roberson on 14 May 2015
colpos = 42; %starting column example
colwid = 7; %column width example
regpat = sprintf('^(?:.{%d}).{%d}', colpos-1, colwid);
filestr = fileread('YourTextFile.txt'); %read file into string
colcontents = regexp(filestr, regpat, 'match', 'lineanchors');
colcontents will now be a cell array of strings, one per entry per line, containing whatever characters were in those columns. If appropriate you can process the cell array further such as by using str2double(colcontents) if you want to interpret them as numbers.


Community Treasure Hunt

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

Start Hunting!

Translated by