【发布时间】:2015-06-08 19:53:57
【问题描述】:
我必须编写一个函数,该函数从 binary file (.dat) 中读取一个二维数组,该数组位于一列中,其名称由函数的单个输入参数提供。该文件的格式如下:
首先,有两个 uint32 数字,分别对应数组的行数和列数。之后,有一个双数,它是数组上非零元素的数量。然后数组的每个非零元素在文件中由两个 uint32 标量和一个 double 标量按以下顺序表示:它的行索引 (uint32)、它的列索引 (uint32) 和它的值 (double)。一个例子可能是:
5
4
2
1
1
8
2
2
9
也就是说数组有5行4列,一共2个非零元素。这些元素将在位置(1,1)(值为8)和位置(2,2)(值为9)中找到。所有其他元素都等于 0。因此,数组将是:
8 0 0 0
0 9 0 0
0 0 0 0
0 0 0 0
0 0 0 0
函数必须返回它从文件中读取的二维数组作为输出参数,如果打开文件有问题,函数返回一个空数组。目前我已尝试使用此代码:
function A = sparse_array_in( filename )
fid = fopen( filename,'rt' );
if fid < 0
A = [];
return;
end
% Get total number of elements on the file
n = 0;
while (fgets(fid) ~= -1),
n = n+1;
end
% Close then reopen
fclose(fid);
fid = fopen( filename,'rt' );
% Read size of array and number of non-zero elements
rows = fread( fid,1,'uint32' );
cols = fread( fid,1,'uint32' );
dims = [ rows,cols ];
non_zero = fread( fid,1,'uint32' );
% Create array of zeros
A = zeros( dims );
% Fill array A with the values from the file
for i = 1:non_zero
r = fread( fid,1,'uint32' );
c = fread( fid,1,'uint32' );
v = fread( fid,1,'double' );
A(r,c) = v;
end
fclose( fid );
end
但它似乎不起作用。我错过了什么?
【问题讨论】:
-
我要写函数,然后提交给老师提供的评分器,这个评分器告诉你这个函数是否正确,但它没有说什么是错误的。我已经尝试了几个小时,但它不起作用,我希望有人能帮我弄清楚我错过了什么,因为我看不到任何错误......
-
您肯定需要创建自己的测试文件,因为您无权访问“grader”文件。从一个非常简单的开始,然后添加一些有明显错误的额外的,看看你的代码是否可以处理它们。