MATLAB: How to read a particular column from a text file

Aerospace Toolboxdigital signal processingprogramming

I am having a text file which is containing a data of text as well as integers from this text i want to read a particular column example I want to read 3rd colum from 10th line can anyone please help me

Best Answer

filename = 'YourFile.txt';
Line_To_Read_From = 10;
Column_To_Read = 3;
[fid, msg] = fopen(filename, 'rt');
if fid < 0
error('Could not open file "%s" because "%s"', filename, msg);
end
for K = 1 : Line_To_Read_From
tline = fgetl(fid);
if ~ischar(tline);
fclose(fid);
error('Failed trying to read line #%d from file "%s"', K, filename);
end
end
fclose(fid)
%guessing that the text might contain whitespace and that the fields are either tab or comma separated
fields = regexp(tline, '[,\t]', 'split');
if length(fields) < Column_To_Read
error('File "%s" only has %d columns on line %d, but we wanted column %d', filename, length(fields), Line_To_Read_From, Column_To_Read);
end
data_text = fields{Column_To_Read};
data_numeric = str2double(data_text);
if isnan(data_numeric)
data = data_text;
else
data = data_numeric;
end
At the end of this, the variable data will contain a numeric value of the desired column could be intepreted as numeric, and otherwise will contain the text, and data_text will contain the raw text.
A lot of the time, the code can be made much more compact, if more is known about how the columns are delimited and about whether the desired data is numeric or txt.
Related Question