How to load a text file in Matlab when the number

2019-09-07 01:29发布

问题:

I have a none rectangular text file like A which has 10 values in first line, 14 values in 2nd line, 16 values in 3rd line and so on. Here is an example of 4 lines of my text file:

line1:

 1.68595314026 -1.48498177528 2.39820933342 27 20 15 2 4 62 -487.471069336 -517.781921387 5 96 -524.886108398 -485.697143555

Line2:

 1.24980998039 -0.988095104694 1.89048337936 212 209 191 2 1 989 -641.149658203 -249.001220703 3 1036 -608.681762695 -300.815673828 

Line3:

 8.10434532166 -4.81520080566 4.90576314926 118 115 96 3 0 1703 749.967773438 -754.015136719 1 1359 1276.73632813 -941.855895996 2 1497 1338.98852539 -837.659179688 

Line 4:

 0.795098006725 -0.98456710577 1.89322447777 213 200 68 5 0 1438 -1386.39111328 -747.421386719 1 1565 -1153.50915527 -342.951965332 2 1481 -1341.57043457 -519.307800293 3 1920 -1058.8828125 -371.696960449 4 1303 -1466.5802002 -308.764587402 

Now, I want to load this text file in to a matrix M in Matlab. I tired to use importdata function for loading it

M = importdata('A.txt');

but it loads the file in a rectangular matrix (all rows have same number of columns!!!) which is not right. The expected created matrix size should be like this:

 size(M(1,:))= 1  10
 size(M(2,:))= 1  14
 size(M(3,:))= 1  16

How can I load this text file in a correct way into Matlab?

回答1:

As @Jens suggested, you should use a cell array. Assuming your file contains only numeric values separated by whitespaces, for instance:

1 3 6
7 8 9 12 15
1 2
0 3 7

You can parse it into cell array like this:

% Read full file
str = fileread('A.txt'); 

% Convert text in a cell array of strings  
c = textscan(str, '%s', 'Delimiter', '\n');
c = c{1};

% Convert 'string' elements to 'double' 
n = cellfun(@str2num, c, 'UniformOutput', false)

You can then access individual lines like this:

>> n{1}

ans =

     1     3     6

>> n{2}

ans =

     7     8     9    12    15


标签: matlab text load