Help with efficient way of importing data file with specific structure

1 次查看(过去 30 天)
Hi, I would like some help to implement an efficient way to import data files with a specific structure to Matlab.
An example of the file I want to import is attached and a figure with some details is presented bellow. The main characteristics are:
1) The first row indicates the numer of variables involved (let's say N).
2) The following N rows indicates the name of the variables.
3) The remainig rows contains the data, which are organized as follows:
a) Each row has a maximum of 6 values (or columns). In this example, where we have 22 variables, 4 rows will be needed (6 + 6 + 6 + 4) to represent the first value for each variable.
b) All variables have the same numer of data.
c) The order of the data is the same of the variables.
The number of variables and associated data can change from file to file, but this structure of the file is always the same.
I was thinking that a cell variable would be a good way to work with the data within Matlab. In this case, this variable would be {22,2}, where the first column would be strings with the data label and the second column would be an array with the data itself.
Could someone help me with this?

采纳的回答

Walter Roberson
Walter Roberson 2020-7-8
filename = 'appropriate_name';
fid = fopen(filename);
nvars = fscanf(fid, '%f', 1);
tdata = textscan(fid, '%[^\n]\n', nvars);
varnames = tdata{1};
fmt = repmat('%f', 1, nvars);
tdata = textscan(fid, fmt);
vardata = cell2mat(tdata);
fclose(fid);
Now varnames is a cell array of character vectors containing everything on the variable lines (possibly including carriage return), and vardata is a something-by-number-of-variables numeric array.
  5 个评论
Walter Roberson
Walter Roberson 2020-7-8
filename = 'Data.txt';
[fid, msg] = fopen(filename);
if fid < 0
error('could not open file "%s" because "%s"', filename, msg);
end
nvars = fscanf(fid, '%f', 1);
tdata = textscan(fid, '%[^\n]\n', nvars);
varnames = tdata{1};
fmt = repmat('%f', 1, nvars);
tdata = textscan(fid, fmt, 'delimiter', '\n');
vardata = cell2mat(tdata);
fclose(fid);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by