ivecs_read.m 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. % Read a set of vectors stored in the ivec format (int + n * int)
  2. % The function returns a set of output vector (one vector per column)
  3. %
  4. % Syntax:
  5. % v = ivecs_read (filename) -> read all vectors
  6. % v = ivecs_read (filename, n) -> read n vectors
  7. % v = ivecs_read (filename, [a b]) -> read the vectors from a to b (indices starts from 1)
  8. function v = ivecs_read (filename, bounds)
  9. % open the file and count the number of descriptors
  10. fid = fopen (filename, 'rb');
  11. if fid == -1
  12. error ('I/O error : Unable to open the file %s\n', filename)
  13. end
  14. % Read the vector size
  15. d = fread (fid, 1, 'int');
  16. vecsizeof = 1 * 4 + d * 4;
  17. % Get the number of vectrors
  18. fseek (fid, 0, 1);
  19. a = 1;
  20. bmax = ftell (fid) / vecsizeof;
  21. b = bmax;
  22. if nargin >= 2
  23. if length (bounds) == 1
  24. b = bounds;
  25. elseif length (bounds) == 2
  26. a = bounds(1);
  27. b = bounds(2);
  28. end
  29. end
  30. assert (a >= 1);
  31. if b > bmax
  32. b = bmax;
  33. end
  34. if b == 0 | b < a
  35. v = [];
  36. fclose (fid);
  37. return;
  38. end
  39. % compute the number of vectors that are really read and go in starting positions
  40. n = b - a + 1;
  41. fseek (fid, (a - 1) * vecsizeof, -1);
  42. % read n vectors
  43. v = fread (fid, (d + 1) * n, 'int=>double');
  44. v = reshape (v, d + 1, n);
  45. % Check if the first column (dimension of the vectors) is correct
  46. assert (sum (v (1, 2:end) == v(1, 1)) == n - 1);
  47. v = v (2:end, :);
  48. fclose (fid);