'Open .mtx file in MATLAB

I have a .mtx file which contains a vector which I am suppose to use for matrix vector multiplication. I tried to open the file using fopen('filename') but this does not work, it returns a single number. I have also tried using readmtx but this gives me the following error: File size does not match inputs. Expected a file size of 232316 bytes. Instead the file size is 365 bytes. Could you please advise how I can open and work with this type of file in MATLAB.



Solution 1:[1]

fopen('filename') outputs only the fileID, which is typically an integer >3. This fileID can be used with e.g. fscanf(fileID) to get the content of the file.

For the .mtx format, where each line contains [row-number column-number matrix-entry], you could also do something like:

%% file
filename = 'my_matrix.mtx';

%% read Matrix
Mat = read_mtx(filename);

%% function
function Mat = read_mtx(filename)
    % open file
    fID = fopen(filename,'r');
    M = fscanf(fID, '%f');
    % reshape M vector into Nx3 matrix
    M = reshape(M, [3, length(M)/3])';
    % assemble final matrix
    Mat = zeros(M(end,1),M(end,1));
    for ii = 1:size(M,1)
        Mat(M(ii,1),M(ii,2)) = M(ii,3);
    end
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fynn