我有以下文字文件:
079082084072079032084069067072000000000,0 082078032049050032067072065082071069000,1 076065066032065083083084000000000000000,0 082078032049050072082000000000000000000,1 082078032049050072082000000000000000000,1 082078032049050072082000000000000000000,1 070083087032073073032080068000000000000,0 080067065032049050032072082000000000000,0 082078032056072082000000000000000000000,1 070083087032073073073000000000000000000,0 082078032087069069075069078068000000000,1 082078032049050072082000000000000000000,1 077065073078084032077069067072032073073,0 082078032049050072082000000000000000000,1 080067065032049050032072082000000000000,0 082078032049050072082000000000000000000,1
我需要太多的矩阵: X尺寸16x13 Y尺寸16x1
我想将文件的每一行分成13个值,例如: 079 082 084 072 079 032 084 069 067 072 000 000 000
是否可以使用 textread 功能将其导入八度?
如果不是,可以使用Linux bash命令完成吗?
答案 0 :(得分:1)
是的,您可以使用textscan
执行此操作(如果您真的想使用textread
,请参阅底部:
octave> txt = "079082084072079032084069067072000000000,0\n082078032049050032067072065082071069000,1";
octave> textscan (txt, repmat ("%3d", 1, 13))
ans =
{
[1,1] =
79
82
[1,2] =
82
78
[1,3] =
84
32
[1,4] =
72
49
[...]
请注意,您正在将它们作为数值读取,因此您不会获得前面的零。如果你想要它们,你可以使用"%3s"将它们作为字符串读取。格式化(因为您将处理单元格数组,因此处理和降低性能会有额外的麻烦)。
因为您正在阅读文件:
[fid, msg] = fopen ("data.txt", "r");
if (fid)
error ("failed to fopen 'data.txt': %s", msg);
endif
data = textscan (fid, repmat ("%3d", 1, 13));
fclose (fid);
如果您真的想使用textread
:
octave> [d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13] = textread ("data.txt", repmat ("%3d", 1, 13))
d1 =
79
82
76
[...]
d2 =
82
78
65
[...]
或:
octave> data = cell (1, 13);
octave> [data{:}] = textread ("data.txt", repmat ("%3d", 1, 13))
data =
{
[1,1] =
79
82
76
[...]
[1,2] =
82
78
65
[...]
如果您需要在逗号后面捕获值(实际上不是原始问题的一部分),您可以使用:
octave> textscan (txt, [repmat("%3d", 1, 13) ",%1d"])
ans =
{
[1,1] =
79
82
[1,2] =
82
78
[1,3] =
84
32
[...]
[1,14] =
0
1
}
答案 1 :(得分:0)
您可以使用shell中的read
一次读取三个字符,从而轻松完成此操作:
while IFS="${IFS}," read -rn3 val tail; do
[[ $tail ]] && echo || printf '%s ' "$val"
done < file
此实现假设如果我们在逗号之后遇到值,我们应该转到下一行。