如何使用textscan()从MATLAB中的.txt文件读取逗号分隔的值? [英] How do I read comma separated values from a .txt file in MATLAB using textscan()?
问题描述
我有一个.txt文件,其中的行由三个元素组成,一个单词和两个数字,以逗号分隔.
I have a .txt file with rows consisting of three elements, a word and two numbers, separated by commas.
例如:
a,142,5
aa,3,0
abb,5,0
ability,3,0
about,2,0
我想读取文件,并将单词放在一个变量中,第一个数字放在另一个变量中,第二个数字放在另一个变量中,但是我在textscan
上遇到问题.
I want to read the file and put the words in one variable, the first numbers in another, and the second numbers in another but I am having trouble with textscan
.
这是我到目前为止所拥有的:
This is what I have so far:
File = [LOCAL_DIR 'filetoread.txt'];
FID_File = fopen(File,'r');
[words,var1,var2] = textscan(File,'%s %f %f','Delimiter',',');
fclose(FID_File);
我似乎无法弄清楚如何在textscan
中使用定界符.
I can't seem to figure out how to use a delimiter with textscan
.
推荐答案
horchler确实是正确的.您首先需要使用 fopen
打开文件,文件ID/指向实际文件的指针.然后,您可以将其与 textscan
一起使用.另外,您实际上只需要一个输出变量,因为一旦使用textscan
,每个列"将作为一个单独的列放置在单元格数组中.您还需要将定界符指定为<c5>字符,因为这是用来分隔列的内容.这是通过使用textscan
中的Delimiter
选项来完成的,并且您将,
字符指定为定界符.使用 fclose
.
horchler is indeed correct. You first need to open up the file with fopen
which provides a file ID / pointer to the actual file. You'd then use this with textscan
. Also, you really only need one output variable because each "column" will be placed as a separate column in a cell array once you use textscan
. You also need to specify the delimiter to be the ,
character because that's what is being used to separate between columns. This is done by using the Delimiter
option in textscan
and you specify the ,
character as the delimiter character. You'd then close the file after you're done using fclose
.
这样,您只需执行以下操作:
As such, you just do this:
File = [LOCAL_DIR 'filetoread.txt'];
f = fopen(File, 'r');
C = textscan(f, '%s%f%f', 'Delimiter', ',');
fclose(f);
请注意,格式化字符串没有空格,因为定界符标志将完成这项工作.不要添加任何空格. C
将包含一个列的单元格数组.现在,如果您想将列拆分为单独的变量,只需访问正确的单元格即可:
Take note that the formatting string has no spaces because the delimiter flag will take care of that work. Don't add any spaces. C
will contain a cell array of columns. Now if you want to split up the columns into separate variables, just access the right cells:
names = C{1};
num1 = C{2};
num2 = C{3};
通过将您在帖子中提供的文本放入名为filetoread.txt
的文件中,这些变量现在看起来像:
These are what the variables look like now by putting the text you provided in your post to a file called filetoread.txt
:
>> names
names =
'a'
'aa'
'abb'
'ability'
'about'
>> num1
num1 =
142
3
5
3
2
>> num2
num2 =
5
0
0
0
0
请注意,names
是名称的单元格数组,因此只需执行n = names{ii};
即可访问正确的名称,其中ii
是您要访问的名称.您将使用普通的索引符号(即n = num1(ii);
或n = num2(ii);
)访问其他两个变量中的值.
Take note that names
is a cell array of names, so accessing the right name is done by simply doing n = names{ii};
where ii
is the name you want to access. You'd access the values in the other two variables using the normal indexing notation (i.e. n = num1(ii);
or n = num2(ii);
).
这篇关于如何使用textscan()从MATLAB中的.txt文件读取逗号分隔的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!