MatLab - How to read a text file separated by ';', with different number of columns [duplicate]

StackOverflow https://stackoverflow.com/questions/17658242

  •  03-06-2022
  •  | 
  •  

Frage

I'm trying to read a .txt file that is ';' delimited with date in the 'header' and diferent columns after the 'header'. I'm using quotes to HEADER because it's more like a parameter line.

So, the .txt is like (the other lines have the same number of columns):

15/07/2013;66;157 
DDD;3;1;0;1;1;1;-0.565
DDD;8;2;0;2;1;1;-0.345 
DDD;9;3;2;3;1;2;-0.643 
DDD;8;1;3;5;1;3;-0.025 
DDD;8;1;0;9;1;4;-0.411 
DDD;15;1;5;4;1;5;-0.09 
DDD;12;1;0;5;1;6;-0.445 
DDD;13;1;0;7;1;7;-0.064

I want to read and create a matrix, that contains each data in one cell, like:

matrix = 
[15/07/2013 66 157
 DDD 3 1 0 1 1 1 -0,565
 DDD 8 2 0 2 1 1 -0,345
 DDD 9 3 2 3 1 2 -0,643
...]

I've tried textscan, cvsread, textread and nothing works!

Thanks in advance!

Edit: Actually, I found a WAY FASTER code to do this!

War es hilfreich?

Lösung

From my past experience, MATLAB does not like strings and numbers to be in the same matrix, so you would be forced to use a cell.

You can do this relatively easily with some simple paring.

fid = fopen('temp.txt','r'); %# open file for reading
count = 1;
content = {};
while ~feof(fid)
    line = strtrim(fgets(fid)); %# read line by line
       parts = regexp(line,';','split');
       for i = 1:numel(parts)
             temp = regexp(parts{i},'-?[0-9]*\.?[0-9]*(i|j)?','match');
             if numel(temp) >= 1 && strcmpi(temp{1},parts{i})
                  parts{i} = str2double(parts{i}) ;
             end
       end
       content{count} = parts;
    count = count + 1;
end
fclose(fid);

numRows  = size(content,2)-1;
whole = cell(numRows,8);
for i = 1:numRows
    for j = 1:8
       whole{i,j} = content{i+1}{j};
    end
end
content = {content{1},whole};

UPDATE

I added some stuff to put everything into a single cell array, all of the data outside of the header. I do not know if you wand the header to also be in that 8 column array, but if you do here is some code to do that

numRows  = size(content,2);
whole = cell(numRows,8);
for i = 1:numRows
    for j = 1:min([size(content{i},2),8])
       whole{i,j} = content{i}{j};
    end
end
whole
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top