2

I have a text file like :

[ 1, 2, 3; 
  2, 4, 5;
  2, 2, 2;
  8, 3, 3 ]

What is the quickest way to load this as a matrix in Octave/Matlab? I want to see this as a matrix with 4 rows and 3 cols.

mkuse
  • 2,250
  • 4
  • 32
  • 61

6 Answers6

1

Drag the text file with your mouse over your workspace in MATLAB (the area where all your current variables are shown) and drop it there. This opens the "import" window:

Import window

Give the file a name (mine is currently "NewTextDocument2") and select IMPORT on the top right. MATLAB will take care of semicolons and brackets. If you want to have a function that does this, select "generate function" instead of IMPORT.

Luca
  • 558
  • 4
  • 18
  • Is there a command which can load it? I have a lot of such files and need to do it programatically – mkuse Oct 26 '14 at 10:46
  • Select "create function" instead of import. This will create a function for you that does the import. You can now change the function a little and have it accept the filename as an argument. – Luca Oct 26 '14 at 10:50
  • look at my second answer. – Luca Oct 26 '14 at 10:57
0

I'm not sure if it is the simplest.

fid = fopen('filename.txt','r');
C = textscan(fid, '%f %f %f', ...
    'Delimiter',' ','MultipleDelimsAsOne', 1);
fclose(fid);
DataMatrix = cat(2,C{:});
Rashid
  • 4,326
  • 2
  • 29
  • 54
0

If your file contains only numbers you can use the Matlab load() function. This function is often used to load .mat files. However it is capable of dealing with what matlab calls ASCII format files.

Say your file is purely textual, contains only numbers and is structured as follows:

filename.txt
  1 2 3 
  2 4 5
  2 2 2
  8 3 3

The load function will create a variable called filename containing your array:

> load('filename.txt');
> filename = 
         [ 1, 2, 3; 
         2, 4, 5;
         2, 2, 2;
         8, 3, 3 ]
JoErNanO
  • 2,458
  • 1
  • 25
  • 27
0

Quick and really dirty approach using the generally non-recommended function eval:

fid = fopen('data.txt');
s = fscanf(fid, '%s');
fclose(fid);
eval(['dataMatrix = ' s ';']);
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

This works with your current format of textfile.

Use this function importfile.m:

function filename = importfile(filename, startRow, endRow)
delimiter = ',';
if nargin<=2
    startRow = 1;
    endRow = inf;
end

formatSpec = '%s%s%s%[^\n\r]';

fileID = fopen(filename,'r');

dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
    frewind(fileID);
    dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
    for col=1:length(dataArray)
        dataArray{col} = [dataArray{col};dataArrayBlock{col}];
    end
end

fclose(fileID);

raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
    raw(1:length(dataArray{col}),col) = dataArray{col};
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));

for col=[1,2,3]
    rawData = dataArray{col};
    for row=1:size(rawData, 1);
        regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\,]*)+[\.]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\,]*)*[\.]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
        try
            result = regexp(rawData{row}, regexstr, 'names');
            numbers = result.numbers;

            invalidThousandsSeparator = false;
            if any(numbers==',');
                thousandsRegExp = '^\d+?(\,\d{3})*\.{0,1}\d*$';
                if isempty(regexp(thousandsRegExp, ',', 'once'));
                    numbers = NaN;
                    invalidThousandsSeparator = true;
                end
            end
            if ~invalidThousandsSeparator;
                numbers = textscan(strrep(numbers, ',', ''), '%f');
                numericData(row, col) = numbers{1};
                raw{row, col} = numbers{1};
            end
        catch me
        end
    end
end

filename = cell2mat(raw);

How to use it:

>> importfile('file.txt',1,4)

ans =

     1     2     3
     2     4     5
     2     2     2
     8     3     3
JoErNanO
  • 2,458
  • 1
  • 25
  • 27
Luca
  • 558
  • 4
  • 18
0

in Octave you could do

fid = fopen ("yourfile", "r");
x = str2num (char(fread(fid))');
fclose (fid)

(I don't know if this works in Matlab)

Andy
  • 7,931
  • 4
  • 25
  • 45