Search Program on this blog

Thursday 27 August 2015

Write a function called sparse_array_in that reads a two-dimensional array of doubles from a binary file whose name is provided by the single input argument of the function. The format of the file is specified in the previous problem. The function returns the two-dimensional array that it reads from the file as an output argument. Note that if you call sparse_array_out with an array called A and then call sparse_array_in using the same filename and save the output of the function in variable B, then A and B must be identical. If there is a problem opening the file, the function returns an empty array.

function A=sparse_array_in(filename)
%Input filename is a binary file
%Output 2D array
fid = fopen(filename,'r');
if fid < 0
    error('error opening file %s\n',filename);
end
r = fread(fid,1,'uint32');%row index
c = fread(fid,1,'uint32');%column index
n = fread(fid,1,'uint32');%value
A=zeros(r,c);
for i=1:n
    row = fread(fid,1,'uint32');
    col = fread(fid,1,'uint32');
    v = fread(fid,1,'double');
    A(row,col)=v;
end
fclose(fid);

No comments:

Post a Comment