Search Program on this blog

Thursday 27 August 2015

Write a function called sparse_array_out that takes two input arguments and returns one output argument. Its first argument is a two-dimensional array of doubles, which it writes into a binary file. The name of that file is the second argument to the function. The file must have the following format. It starts with three uint32 scalars specifying the number of rows of the array followed by the number of columns followed by the number of non-zero elements in the array. Then each non-zero element of the array is represented by two uint32 scalars and a double scalar in the file in this order: its row index (uint32), its column index (uint32), and its value (double). Note that this file format is an efficient way to store a so-called “sparse array”, which is by definition an array for which the overwhelming majority of its elements equal 0. The function’s output argument is of type logical and equals false if there was a problem opening the file and true otherwise.

function out = sparse_array_out(A,filename)
%Input A is 2D array and filename is a binary file
%Output out is logical value
fid = fopen(filename,'w+');
if fid < 0
    out=0;
    return;
end
dims = size(A);
[row,col,v] = find(A);
n=length(v);
fwrite(fid,dims(1),'uint32');
fwrite(fid,dims(2),'uint32');
fwrite(fid,n,'uint32');
for i=1:n
    fwrite(fid,[row(i),col(i),],'uint32');
    fwrite(fid,v(i),'double');
end
out=1;
fclose(fid);

No comments:

Post a Comment