USAGE: writePetscBin(filename,X,multiVec,isBig) Function to write a vector or matrix to PETSc binary format INPUTS: filename: name of file to write vector/matrix to X: vector or sparse matrix multiVec: If X has more than one column, multiVec=1 indicates that X each column of X is a vector. isBig: flag to force script to call a mex function when writing out a sparse matrix. Use this option for large matrices. To use this option you must have the mex function 'writePetscBinaryMat_mex.mexXXX' in your path. Samar Khatiwala (spk@ldeo.columbia.edu) This function is based on code originally written by Antti.Vanne@uku.fi
0001 function writePetscBin(filename,X,multiVec,isBig) 0002 0003 % USAGE: writePetscBin(filename,X,multiVec,isBig) 0004 % Function to write a vector or matrix to PETSc binary format 0005 % INPUTS: 0006 % filename: name of file to write vector/matrix to 0007 % X: vector or sparse matrix 0008 % multiVec: If X has more than one column, multiVec=1 0009 % indicates that X each column of X is a 0010 % vector. 0011 % isBig: flag to force script to call a mex function when 0012 % writing out a sparse matrix. Use this option for 0013 % large matrices. 0014 % To use this option you must have the mex function 0015 % 'writePetscBinaryMat_mex.mexXXX' in your path. 0016 % Samar Khatiwala (spk@ldeo.columbia.edu) 0017 % This function is based on code originally written by Antti.Vanne@uku.fi 0018 0019 if nargin<3 0020 multiVec=0; 0021 end 0022 if isempty(multiVec) 0023 multiVec=0; 0024 end 0025 0026 if nargin<4 0027 isBig=0; 0028 end 0029 if isempty(isBig) 0030 isBig=0; 0031 end 0032 0033 MAT_FILE_COOKIE=1211216; 0034 VEC_FILE_COOKIE=1211214; 0035 0036 if (size(X,2) == 1) || (multiVec==1) 0037 if ~isBig 0038 % X is a vector 0039 % disp('Saving vector..'); 0040 fid=fopen(filename,'w','ieee-be'); 0041 nv=size(X,2); 0042 for it=1:nv 0043 fwrite(fid,VEC_FILE_COOKIE,'int'); 0044 fwrite(fid,size(X,1),'int'); 0045 fwrite(fid,full(X(:,it)),'float64'); 0046 end 0047 fclose(fid); 0048 % disp(['Wrote ' num2str(nv) ' vectors']) 0049 0050 else 0051 % disp('using mexfile') 0052 writePetscBinaryVec_mex_c(filename,X'); 0053 end 0054 else 0055 % X is a matrix 0056 % disp('Saving matrix'); 0057 if ~isBig 0058 fid=fopen(filename,'w','ieee-be'); 0059 [M,N]=size(X); 0060 fwrite(fid,MAT_FILE_COOKIE,'int'); 0061 fwrite(fid,M,'int'); 0062 fwrite(fid,N,'int'); 0063 fwrite(fid,nnz(X),'int'); 0064 [ii,jj,aa]=find(X'); 0065 % nonzeros in each row 0066 nnzrow=zeros(size(X,1), 1); 0067 % for kk = 1:M 0068 % nnzrow(kk) = nnz(jj==kk); % slow 0069 % nnzrow(kk) = length(find(jj==kk)); % faster 0070 % end 0071 nnzrow(:)=full(sum(spones(X'))'); % fastest 0072 fwrite(fid,nnzrow,'int'); 0073 fwrite(fid,ii-1,'int'); 0074 fwrite(fid,aa,'float64'); 0075 else 0076 % disp('using mexfile') 0077 writePetscBinaryMat_mex_c(filename,X') 0078 end 0079 end