Read first column from the text file

조회 수: 24 (최근 30일)
Vincy Y
Vincy Y 2019년 2월 6일
댓글: Asko Köhn 2021년 3월 8일
I have a text file that contains eighty rows with six columns of data values. All I want to do is read a first column of values only. How do I read the column ?
  댓글 수: 1
Nuwan Liyanage
Nuwan Liyanage 2020년 3월 30일
% Assigning the path
path = 'C:\Users\User\abc\'; %abc is your folder which contains the txt file
% Assigning a variable to access the file
fileName = [path,'xyz.txt'];
% Importing all the data from the txt file
fileEntireDataSet = importdata(FileName);
% Assigning the first column only
dataFirstColumn = fileEntireDataSet.data(:,1);

댓글을 달려면 로그인하십시오.

채택된 답변

madhan ravi
madhan ravi 2019년 2월 6일
fid = fopen('sample.txt')
% ^^^^^^^^^^----- your filename
formatspec=['%f',repmat('%*f',1,5)]; % 5 represents total columns - the first column
data = textscan(fid,formatspec);
fid = fclose(fid);
data{:} % first column
  댓글 수: 3
Vincy Y
Vincy Y 2019년 2월 6일
Yes, it is work, thanks to you,
Asko Köhn
Asko Köhn 2021년 3월 8일
All format specifiers for textscan() are also supported in readtable(), so the suggested solution by textscan(fileID,...) could also less verbosely be implemented with readtable():
col_1 = readtable('sample.txt', 'Format','%f %*f %*f %*f %*f %*f');
Or for a known header of the first column e.g. 'header_1':
opts = detectImportOptions('sample.txt');
opts.SelectedVariableNames = {'header_1'};
col_1 = readtable('sample.txt', opts);
which can be really useful for extraction of a few columns from files containing a greater number of columns.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by