Hello all, I am a beginner in matlab. I’m trying to import specific rows from a .txt file where the file format is unknown. Actually, the existing solutions allow me only to get rows instead of columns. For example, I want to read from the attached file, the column n=2 that includes (V1 D3 6.52 4.91 3.00 2.05 0.69 NAN NAN NAN) and to store the result into an array.
MATLAB: Read specific column from .txt file with unkown format
textscanunknown_format
Related Solutions
What part are you not able to make more versatile?
If you know a priori the number of columns, you can make the following changes
function data = Load_Data( filename, strain_command_data, nCol ) if nargin < 3 nCol = 5 ; % Default.
end formatSpec = repmat( '%f', 1, nCol ) ; FID = fopen( filename ) ; data = textscan( FID, formatSpec, 'HeaderLines', 5, 'CollectOutput', 1 ) ; .. etc. end
If you don't know a priori the number of lines, you could determine it based on one line of the header. If the file had the following content
Header line 1.. Header line 2.. dataID time x y 1 120 8.7 9.1
you could determine that there are 4 columns based on the 3rd line of the header which contains column labels..
function data = Load_Data( filename, strain_command_data ) fid = fopen( filename, 'r' ) ; fgetl( fid ) ; % Skip line 1.
fgetl( fid ) ; % Skip line 2.
colLabels = fgetl( fid ) ; nCol = numel( regexp( colLabels, '\s+' )) + 1 ; formatSpec = repmat( '%f', 1, nCol ) ; data = textscan( fid, formatSpec, 'CollectOutput', 1 ) ; .. etc. end
EDIT: see my second solution for a more flexible approach.
=== 1st solution.
% - Read content.
fid = fopen( 'myFile.txt', 'r' ) ; content = fscanf( fid, '%f', Inf ) ; fclose( fid ) ; % - Extact headers and data.
colHeader = content(1:6).' ; content = reshape( content(7:end), 7, [] ).' ; rowHeader = content(:,1) ; data = content(:,2:end) ;
With that, you get..
>> colHeader colHeader = 0 10 25 50 75 100 >> rowHeader rowHeader = 290 291 >> data data = 0 0.1000 0.1200 0.1500 0.2000 0.3000 0 0.1100 0.1210 0.1510 0.2100 0.3100
PS: there are other approaches, e.g. based on FGETL for the col. header and then TEXTSCAN, but I personnaly prefer reading the file in one shot and then reshaping/extracting numbers appropriately.
=== 2nd solution.
If the number of columns could vary among files though, I would go for a first step reading the first line of the file and determining dynamically the number of columns, before reading/processing the rest. For example:
fid = fopen( 'myFile.txt', 'r' ) ; colHeader = sscanf( fgetl(fid), '%f' ).' ; % Read/convert 1st line only.
nDataCol = numel( colHeader ) ; % Determine # of data columns.
content = fscanf( fid, '%f', Inf ) ; % Read rest of the file.
fclose(fid) ; content = reshape( content, nDataCol+1, [] ).' ; rowHeader = content(:,1) ; data = content(:,2:end) ;
Best Answer