我有一个形式的数据集
0.547,0.797,2.860,1.398,Sharp-Right-Turn 0.541,0.786,2.373,1.919,Sharp-Right-Turn 0.549,0.784,2.370,1.930,Sharp-Right-Turn 0.983,0.780,2.373,1.701,Move-Forward 0.984,0.780,2.372,1.700,Move-Forward 0.983,0.780,2.378,1.602,Move-Forward 0.983,0.780,2.381,1.701,Move-Forward . . ROWS=5456, COL 5
Its easy in MATLAB to load the text file into a data matrix. But am struggling in C. I tried this code
int main()
{
struct node {
float at1;
float at2;
float at3;
float at4;
char at5[30];
} record[ROW][COL];
FILE *file;
int i, j;
memset(record, 0, sizeof(record));
file = fopen("sensor.txt", "r");
if (file == NULL) {
printf("File does not exist!");
} else {
for (i = 0; i < ROW; ++i) {
for (j = 0; j < COL; ++j) {
fscanf(file, "%f,%f,%f,%f,%s", &record[i][j].at1, &record[i][j].at2, &record[i][j].at3, &record[i][j].at4, &record[i][j].at5);
}
}
}
fclose(file);
for (i = 0; i < ROW; ++i)
for (j = 0; j < COL; ++j) {
printf("%f\t%f\t%f\t%f\t%s\n", record[i][j].at1, record[i][j].at2, record[i][j].at3, record[i][j].at4, record[i][j].at5);
}
return 0;
}
我只得到无限行和 4 列 0.000000
。
我想将前四列保存在一个矩阵中,将最后一列保存为另一个列矩阵。我可以这样做吗?
我必须构建一个分类器,我可以在 MATLAB 中轻松完成该分类器,而无需使用预定义函数,但在 C 中读取数据会妨碍我的代码。
我知道这可能是一个重复的问题,但我尝试了其他线程中的解决方案,它们不适用于我的数据集。
最佳答案
首先,您定义了一个包含所有字段的记录,这些字段一起形成每一行。这意味着当您读取时,您拥有一行的所有值,因此结构维度应该是可用的最大记录,即单维结构数组记录
。
但是你不能在堆栈上分配这么大的结构,它会溢出,最好将它分配在动态内存中:
struct node {
float at1;
float at2;
float at3;
float at4;
char at5[30];
} record;
struct node *record = malloc(sizeof(struct node) * MAXRECORDS);
另一个错误是在 scanf
中,结构体 record
的最后一个字段已经是一个指向 char 的指针,因此不需要取消引用它。
这是一个工作代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRECORDS 10
int main(int argc, char *argv[])
{
struct node {
float at1;
float at2;
float at3;
float at4;
char at5[30];
};
struct node *record = malloc(sizeof(struct node) * MAXRECORDS);
FILE *file;
int nRecords = 0;
memset(record, 0, sizeof(record));
file = fopen("sensor.txt", "r");
if (file == NULL)
{
printf("File does not exist!");
}
else
{
while (EOF != fscanf(file, "%f,%f,%f,%f,%s", &record[nRecords].at1, &record[nRecords].at2,
&record[nRecords].at3, &record[nRecords].at4, record[nRecords].at5) && nRecords<MAXRECORDS)
{
nRecords++;
}
}
fclose(file);
for (int i = 0; i < nRecords; ++i)
{
printf("%f\t%f\t%f\t%f\t%s\n",
record[i].at1, record[i].at2,
record[i].at3, record[i].at4, record[i].at5);
}
return 0;
}
在“真实”应用程序中,您希望将数组的维度设置为足够大的值,并且当到达分配空间的末尾时,您可以将其重新分配给其他数据。这允许您读取一个文件,其中包含您想要的条目数,而无需在读取之前知道它们的数量。
附注我添加了对要读取的最大记录数的检查。但这仍然是一个示例,仍然缺少许多检查,即我不检查 malloc 返回的值。
关于c - 如何将数据集从文本文件读取到二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32117743/