I want to read this text file from Matlab directly and want to import data of all columns into work space in an array.

1 回表示 (過去 30 日間)
fid = fopen('1.txt');
a = textscan(fid,'%s%s%s%s%s%s%s','Delimiter','','Headerlines',4);
lines=a{1:7};
fclose(fid)

採用された回答

Walter Roberson
Walter Roberson 2016 年 10 月 5 日
Your file appears to contain 10 lines. You ask to skip the first 4, which would leave 6. You then ask to read 7 lines. You are going to have difficulty with the 7th value.
  3 件のコメント
Walter Roberson
Walter Roberson 2016 年 10 月 5 日
fid = fopen('1.txt', 'rt');
datacell = textscan(fid, '%s%s%f%f%f%f%f', 'HeaderLines',3);
fclose(fid);
timestamps = strjoin(datacell{1}, {' '}, datacell{2});
numerics = cell2mat(datacell(3:end));
Walter Roberson
Walter Roberson 2016 年 10 月 6 日
You can then convert the timestamps to datetime objects with
datetime(timestamps, 'Format', 'yy-MM-dd HH:mm')

サインインしてコメントする。

その他の回答 (2 件)

Jeremy Hughes
Jeremy Hughes 2016 年 10 月 5 日
I suggest the 'CollectOutput' parameter
fid = fopen('1.txt');
a = textscan(fid, '%s%s%s%s%s%s%s', 'Delimiter', '', 'Headerlines', 4, 'CollectOutput', true);
lines = a{1};
fclose(fid)
Also, if you're trying to read just lines, this will work:
fid = fopen('1.txt');
a = textscan(fid, '%[^\r\n]', 'EndOfLine', '\r\n', 'Headerlines', 4, 'Delimiter', '','Whitespace','');
lines = a{1};
fclose(fid);
Your first code might work for the file you have, but the second block is a more robust version for line reading if you have leading spaces, or if you want to capture empty lines.

Wei-Rong Chen
Wei-Rong Chen 2016 年 10 月 5 日
編集済み: Walter Roberson 2016 年 10 月 6 日
It will be much easier if you use 'readtable' function. For example:
dataTable = readtable('1.txt','Delimiter',your_delimiter,'ReadVariableNames',set_true_if_first_row_is_VarNames);
num_array = table2array(dataTable(:,1:7));
  2 件のコメント
Walter Roberson
Walter Roberson 2016 年 10 月 5 日
In R2016b, readtable will interpret the date string '15-04-01' as a date 0015-04-01 unless you specify 'datetimetype', 'text'.
It is possible to specify a format for readtable for the date handling
readtable('1.txt', 'format', '%{yy-MM-dd}D%{HH:mm}D%f%f%f%f%f')
Unfortunately for this purpose it does not seem to be possible to grab the date and time as a single entity, so you end up with two datetime objects in the output and you cannot just add them together.
Walter Roberson
Walter Roberson 2016 年 10 月 5 日
If you use
t = readtable('1.txt', 'format', '%{yy-MM-dd}D%{HH:mm}D%f%f%f%f%f');
then
timestamps = t.Var2 - dateshift(t.Var2, 'begin', 'day') + t.Var1;
This takes into account several arcane behaviours of datetime objects.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by