正确设置textscan返回空单元格数组 [英] Properly set textscan returns empty cell array
问题描述
我有一个.txt文件,格式为:
I have a .txt file in the format of:
123123 4
123234 4
515511 4
157888 4
854634 4
345661 4
我希望能够将每一列导入不同的变量.我尝试过:
I want to be able to import each column into a different variable. I've tried:
data = textscan(fid, '%f %*[^\n]','HeaderLines',0);
test = textscan(fid, '%*f %f %*[^\n]','HeaderLines',0);
成功导入数字的第一列,但是test
返回[]
.
Which successfully imports the first column of numbers however test
returns []
.
是什么原因造成的?
推荐答案
此刻您正在扫描整个文件两次 -这不是一个好主意.
At the moment you're scanning the whole file two times - that's not a good idea.
那 导入 在一个变量中然后将其拆分?
So how about importing everything in one variable and splitting it up afterwards?
DATA = importdata('myFile.txt',' ',0)
data = DATA(:,1);
test = DATA(:,2);
clear DATA
请注意,如果您有标题行,则代码会有所不同:
Be aware that if you have headerlines, the code varies a little:
headerlines = 5
DATA = importdata('myData.txt',' ',headerlines)
data = DATA.data(:,1);
test = DATA.data(:,2);
如果空白分隔符' '
不起作用,请尝试制表符'/t'
.
If the white space delimiter ' '
is not working, try tabulator '/t'
.
您的方法不起作用的原因是文件ID fid
.想象fid
是一包美味的奶酪.通过textscan读取的文件的每一行就像您已经吃了一片奶酪.因此,在您执行命令之后:
The reason why your approach is not working is the file-ID fid
. Imagine fid
is a pack of tasty cheese. Every line of the file which got read by textscan is like you have eaten one slice of cheese. So after your command:
data = textscan(fid, '%f %*[^\n]','HeaderLines',0);
没有奶酪了.而且您的第二个textscan
通话没有任何操作.要使其正常工作,您需要打开另一包类似的奶酪:
there is no cheese left. And your second textscan
call is left without any cheese. To make it work you would need to open another similar pack of cheese:
fid = fopen('myData.txt');
data = textscan(fid, '%f %*f %*[^\n]','HeaderLines',0);
fclose(fid)
fid = fopen('myData.txt');
test = textscan(fid, '%*f %f %*[^\n]','HeaderLines',0);
fclose(fid)
但是我告诉你,你会发胖.但是,如果您真的想吃奶酪,请按照以下步骤操作:
But I tell you, you will get fat. But if you really want to eat cheese, do it as follows:
fid = fopen('myData.txt');
DATA = textscan(fid, '%f %f %*[^\n]','HeaderLines',0);
fclose(fid)
data = DATA(1);
test = DATA(2);
这篇关于正确设置textscan返回空单元格数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!