将文本值从 ASCII 文件读入 matlab 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/259968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:41:04  来源:igfitidea点击:

Reading text values into matlab variables from ASCII files

matlabtextfile-iotext-filestext-processing

提问by Boris Gorelik

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.

我不介意将名称和数字分成两个文件,但是准备 matlab 代码文件并对其进行评估不是一种选择。

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

请注意,可以有任意数量的变量(列)

回答by Adam Holmberg

I suggest importdatafor 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'.

返回是一个结构体,在名为“data”的成员中包含数字字段,在名为“colheaders”的字段中包含列标题。

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

另一个用于导入操作数据的有用界面是“统计工具箱”中提供的“数据集”类。

回答by Azim

If the header is on the first row then

如果标题在第一行,那么

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

will read the numeric data into the Matrix A.

将数值数据读入矩阵 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 strtokto split the headerString into a cell array. Is one approach I can think of deal with an unknown number of columns

然后,您可以使用strtok将 headerString 拆分为元胞数组。我能想到的一种方法是处理未知数量的列

编辑

fixed fscanf function call

固定 fscanf 函数调用

回答by Robert Van Hoose

Just use textscan with different format specifiers.

只需使用具有不同格式说明符的 textscan 即可。

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.

在这种情况下,'heading' 将是一个包含单元格的单元格数组,其中包含每个列标题,因此您必须将它们更改为字符串单元格数组或您想要的任何内容。'data' 将是一个元胞数组,其中包含您读取的每一列的数值数组,因此您必须将它们组合在一起以形成一个矩阵。