Read first column from the text file

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 日

0 投票

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 件のコメント

madhan ravi
madhan ravi 2019 年 2 月 6 日
Honestly I would read the full text file :
data=load('sample.txt'); % assuming you only have data values(numbers)
data(:,1) % and jus extract the first column
% or
data=readtable('sample.txt'); % requires 2013a or later
data(:,1) % table with one column which is the first column
data{:,1} % just numbers in the first column
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 件)

タグ

質問済み:

2019 年 2 月 6 日

コメント済み:

2021 年 3 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by