Azzera filtri
Azzera filtri

Help with efficient way of importing data file with specific structure

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

Walter Roberson
Walter Roberson il 8 Lug 2020
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 Commenti
Walter Roberson
Walter Roberson il 8 Lug 2020
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);

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Prodotti


Release

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by