我用这个:
weights=fopen('indices.txt');
weights=textscan(weights, '%d %d %d %d %d %d %d')
但这只会读取我文件的第一行。我的文件如下所示:
0 90 100 5 0 0 0 (class)
19 5 0 0 0 0 0 (class2)
5 5 0 0 0 0 0 (class3)
-10 -5 0 0 0 0 0 (class4)
而且我不需要括号中的内容
非常感谢 !
对于这种情况,您可以执行以下操作:
fid = fopen('indices.txt');
num_ints = 7;
num_rows = 4;
format = [repmat('%d ', 1, num_ints), '%s'];
weights = textscan(fid, format, num_rows);
weights = [weights{1:num_ints}];
fclose(fid);
当然,缺点是你必须事先知道你正在阅读的行数。您可以尝试在循环中调用 textscan ,但这似乎不是它的用途(如果我试图逐行读取文件,我宁愿使用 fgetl 代替)。
使用以下内容:
fh = fopen('indices.txt');
resC = textscan(fh, '%d %d %d %d %d %d %d %s', 1000);
res = cell2mat(resC(1:7))
fclose(fh);
textscan
只会读取(并返回)最多可用的行数。但是请注意,这会textscan
为您提供的行数(此处为 1000)分配内存,因此您想在那里选择“明智”的东西。