当每行中的值数量不同时,如何在Matlab中加载文本文件 [英] How to load a text file in Matlab when the number of values in every line are different

查看:112
本文介绍了当每行中的值数量不同时,如何在Matlab中加载文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非矩形的文本文件,例如A,在第一行中有10个值,在第二行中有14个值,在第三行中有16个值,依此类推.这是我的文本文件的4行示例:

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:

第1行:

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

第2行:

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

第3行:

 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 

第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 

现在,我想将此文本文件加载到Matlab中的矩阵M中.我厌倦了使用importdata函数进行加载

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

如何以正确的方式将此文本文件加载到Matlab中?

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

推荐答案

按照@Jens的建议,您应该使用单元格数组.假设您的文件仅包含用空格分隔的数字值,例如:

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中加载文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆