I imported a text file with 3 column using importdata function. Now I want to pull out column 3 from the text file. How Do I do it ?
MATLAB: Extracting column from text file
txt file
Related Solutions
You forgot to attach the file, but basically I'm guessing you'd do:
data = importdata(filename);% Non-loop way:
data10 = data(1:10:end, :);% Loop way
[rows, columns] = size(data);data10 = zeros(ceil(rows/10), columns);thisRow = 1;for row = 1 : 10 : rows data10(thisRow, :) = data(row, :); thisRow = thisRow + 1;end
This is a fixed-width text file. The documentation includes a good description on how to read fixed-width text files.
See
- fixedWidthImportOptions, Import options object for fixed-width text files.
- read ASCII data with varying lengths of space as delimiters
Be careful to get the column widths right.
Also,
- how to extract the USAF entries corresponding to only CTRY==AF ?
- how to extract all the rows with rowNumber=10000 to rowNumber=20000 (say).
Use readtable() and read all rows (if that doesn't cause memory problems). The tools you need comes with table.
In response to comments
Since there are no delimiters in the data file, I find the message
Line 3 has 9 delimiters, while preceding lines have 8.
misleading. Even if one sequences of char(32) is counted as one delimiter the numbers 9 and 8 doesn't make sense.
I created the script below in three steps
- Create the obj, opts, with default values. Inspect opts
- Type opts.<tab> in the Command Window. (<tab> stands for tab-completion). I identified four properties, the default values of which were not meaningsful. I added statements to the script to assign values, which I found in the comments. (To save me some trouble in the future, I modified the names to become legal Matlab names.)
- Read the file with readtable().
%%
ffs = fullfile('d:\m\cssm\noaa1lineHeaderFirst15lines.txt');opts = fixedWidthImportOptions; % default values
%%opts.DataLines = [ 2, inf ];opts.VariableNames = { 'USAF','WBAN','STATION_NAME','CTRY','ST' ... , 'CALL','LAT','LON','ELEV_M_','BEGIN','END' };opts.VariableTypes = { 'double','double','char','char','char','char' ... , 'double','double','double','double','double' };opts.VariableWidths = [ 7, 6, 30, 5, 3, 6, 8, 9, 8, 9, 9 ];%%tbl = readtable( ffs, opts );
No eror messages so far.
>> tbltbl = 14×11 table USAF WBAN STATION_NAME CTRY ST CALL LAT LON ELEV_M_ BEGIN END _____ _____ _____________________ ____ __ ______ ______ ______ _______ __________ __________ 7018 99999 'WXPOD 7018' '' '' '' 0 0 7018 2.011e+07 2.0131e+07 7026 99999 'WXPOD 7026' 'AF' '' '' 0 0 7026 2.0121e+07 2.0171e+07 7070 99999 'WXPOD 7070' 'AF' '' '' 0 0 7070 2.0141e+07 2.0151e+07 8260 99999 'WXPOD8270' '' '' '' 0 0 0 2.005e+07 2.0101e+07 8268 99999 'WXPOD8278' 'AF' '' '' 32.95 65.567 1156.7 2.0101e+07 2.012e+07 8307 99999 'WXPOD 8318' 'AF' '' '' 0 0 8318 2.01e+07 2.01e+07 8411 99999 'XM20' '' '' '' NaN NaN NaN 2.016e+07 2.016e+07 ...
Looks ok
Best Answer