savebinary.m 918 B

1234567891011121314151617181920212223242526272829303132333435
  1. function savebinary(file,precision,m,wantappend)
  2. % function savebinary(file,precision,m,wantappend)
  3. %
  4. % <file> is a file location
  5. % <precision> is something like 'int16'
  6. % <m> is a matrix
  7. % <wantappend> (optional) is whether to append to <file>. default: 0.
  8. %
  9. % write <m> to <file>. for the machine format, we use IEEE floating
  10. % point with little-endian byte ordering (see fopen).
  11. %
  12. % see also loadbinary.m.
  13. %
  14. % example:
  15. % savebinary('test','uint8',repmat(0:255,[2 1]));
  16. % isequal(loadbinary('test','uint8',[0 256],[255 256]),repmat([254 255],[2 1]))
  17. % constants
  18. machineformat = 'l';
  19. % input
  20. if ~exist('wantappend','var') || isempty(wantappend)
  21. wantappend = 0;
  22. end
  23. % open file
  24. fid = fopen(file,choose(wantappend,'a','w'),machineformat);
  25. assert(fid ~= -1,'<file> could not be opened for writing');
  26. % do it
  27. assert(fwrite(fid,m,precision,0,machineformat)==prod(size(m)));
  28. % close file
  29. assert(fclose(fid)==0);