image thumbnail

Loader of a .txt file to a MATLAB matrix

by

 

01 Jun 2011 (Updated )

Loads a content of a .txt file and stores it in a MATLAB matrix

txt2mat(data)
function A = txt2mat(data)
% author: Luka Lukic ------------------------------------------------------
% input: data - string file with path of a .txt file, e.g 'data.txt'
% output: matrix - matrix of data stored
%--------------------------------------------------------------------------
if ischar(data)
    fid = fopen(data, 'r');
else
    disp('Error: parametar is not a string!');
    A = 0;
    return 
end

stringline = fgetl(fid);
vector = str2num(stringline);

len = length(vector);
ir = 1;
A = zeros(ir, len);

while ischar(stringline)  
    vector = str2num(stringline);
    for i = 1 : len
        A(ir, i) = vector(i);
    end
    ir = ir + 1;
    stringline = fgetl(fid);
end
fclose(fid);

Contact us