Reading text values into matlab variables from ASCII files

*爱你&永不变心* 提交于 2019-12-23 08:54:29

问题


Consider the following file

var1 var2 variable3
1     2    3
11    22   33

I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:

variable_names = char('var1', 'var2', 'variable3');

I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option.

Note that there can be an arbitrary number of variables (columns)


回答1:


I suggest importdata for operations like this:

d = importdata('filename.txt');

The return is a struct with the numerical fields in a member called 'data', and the column headers in a field called 'colheaders'.

Another useful interface for importing manipulating data like these is the 'dataset' class available in the Statistics Toolbox.




回答2:


If the header is on the first row then

A = dlmread(filename,delimString,2,1);

will read the numeric data into the Matrix A.

You can then use

fid = fopen(filename)
headerString = fscanf(fid,'%s/n') % reads header data into a string
fclose(fid)

You can then use strtok to split the headerString into a cell array. Is one approach I can think of deal with an unknown number of columns

Edit

fixed fscanf function call




回答3:


Just use textscan with different format specifiers.

fid = fopen(filename,'r');
heading = textscan(fid,'%s %s %s',1);
fgetl(fid); %advance the file pointer one line
data = textscan(fid,'%n %n %n');%read the rest of the data
fclose(fid);

In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.



来源:https://stackoverflow.com/questions/259968/reading-text-values-into-matlab-variables-from-ascii-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!