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