matlabfile-import

Import matlab with space and tab delimiter


I need to import a txt file into Matlab which has this format

text text text           
1           0 1 2 3
            4 5 6 7
2           10 11 15 18
            15 1 18 3

The first column is separated with the second one by a tab delimiter, while the rest of the data are separated by a space. I tried to import it using this:

g = importdata('file.txt',delimiterIn,headerlinesIn);
delimiterIn = ' ';
headerlinesIn = 1;

but then the extracted table is like this:

text text text  
1 0 1 2 3
4 5 6 7 nan
2 10 11 15 18
15 1 18 3 nan

What I want is a table that maintains the format, with the first column of g.data on its own and then all the others.

I want an output matrix like

1 0 1 2 3
  4 5 6 7
2 10 11 15 18
  15 1 18 3

Then if I need to extract data represented by 2 in the first column, I can put it into another matrix with the values

10 11 15 18
15 1 18 3

each number inside a cell of a matrix

How can I do it?


Solution

  • A sollution might be:

    fid = fopen('test.txt');
    M = {[]};Midx=1;
    l = fgetl(fid); %header
    l = fgetl(fid);
    while ~isnumeric(l)
        idx = str2double(l(1));
        if ~isnan(idx)
            Midx=idx;
            M{Midx}=[];
            l = l(2:end);
        end
        val = cell2mat(textscan(l,'%f'))';
        M{Midx}=[M{Midx};val];
        l=fgetl(fid);
    end
    fclose(fid);