Commit d994db97ad774a9d70ffee476e024214778cfe02

Authored by Brendan Klare
1 parent e9030443

Function to load mtx file into matlab

Showing 1 changed file with 59 additions and 0 deletions
scripts/matlab/loadMtx.m 0 → 100644
  1 +function [x2] = loadMtx(filename,isRowMajor)
  2 +% [x2] = loadMtx(filename,reverse)
  3 +%
  4 +% Loads a *.mtx file into a Matlab matrix.
  5 +% 'filename' - the name of the mtx file
  6 +% 'isRowMajor' - determines whether the
  7 +% matrix is read in row major or
  8 +% column major order (optional, default is false)
  9 +%
  10 +% This file can likely be improved in terms of effeciency.
  11 +
  12 +
  13 + if nargin < 2,
  14 + reverse = false;
  15 + end
  16 +
  17 + z = fopen(filename,'r');
  18 + if z == -1,
  19 + fprintf('Error opening file %s\n',filename);
  20 + x2 = 0;
  21 + return
  22 + end
  23 +
  24 + buf = zeros(100,1);
  25 + str_list = cell(4,1);
  26 + for i = 1:4,
  27 + cnt = 0;
  28 + while true
  29 + cnt = cnt + 1;
  30 + [a ] = fread(z,1,'uchar');
  31 + if a == 10
  32 + break;
  33 + end
  34 + buf(cnt) = a;
  35 + end
  36 + str_list{i} = char(buf(1:cnt-1)');
  37 + end
  38 +
  39 + s = strsplit(' ',str_list{4});
  40 + x = str2num(s{2});
  41 + x1 = str2num(s{3});
  42 + typ = s{1}(2);
  43 +
  44 + %x2 = fread(z,[x1 x],'float32');
  45 + if strcmp(typ,'F')
  46 + x2 = fread(z,[x1 x],'single');
  47 + elseif strcmp(typ,'B')
  48 + x2 = fread(z,[x1 x],'int8');
  49 + else
  50 + assert(0);
  51 + end
  52 + x2 = x2';
  53 + fclose(z);
  54 +
  55 + if reverse,
  56 + sz = size(x2);
  57 + x2 = x2';
  58 + x2 = reshape(x2,sz);
  59 + end
... ...