将数据块读入Matlab数组 [英] Read block of data into matlab array
问题描述
我的数据文件如下所示
3 1.0 1.4 1.7
2 1.2 1.5
1 1.1
2 1.1 1.2
对于每一行,第一个整数表示此行中的浮点数.
For each line, the first integer indicates the number of floating numbers in this line.
现在我想将所有数据加载到单个matlab数组中,并忽略第一列,也就是说,我想获得一个像这样的数组
Now I want to load all the data into a single matlab array, and ignore first column, that is, I want to get a array like this
>>arr = [1.0, 1.4, 1.7, 1.2, 1.5, 1.1, 1.1, 1.2]
如果每一行都有相同数量的浮点数,我可以这样简单地完成
if for each line, we have same number of floating numbers, I can simply do it like this
>>arr = load datafile ;
>>arr = arr(:,2:end) ; %ignore the first column
>>arr = arr(:) ;
但是,如果每行中有不同数量的浮点数,则似乎无法直接将文件加载到矩阵中.有没有简单的方法可以做到这一点?
However, if we have different number of floating numbers in each line, it seems we cannot directly loaded the file into a matrix. Is there any simple way to accomplish this ?
谢谢.
推荐答案
首先,让我们以字符串形式读取数字:
First, let's read the numbers as strings:
C = textread('myfile.txt', '%s', 'delimiter', '\n');
结果是一个字符串单元格数组,因此让我们在每个单元格上应用str2num
以获得数值:
The result is a cell-array of strings, so let's apply str2num
on each cell to obtain numerical values:
C = cellfun(@str2num, C, 'Uniform', false);
现在让我们丢弃每个单元格中的第一个元素:
Now let's discard the first element from each cell:
C = cellfun(@(x)x(2:end), C, 'Uniform', false);
最后,我们将所有值连接到一个向量中:
Finally, we concatenate all values into one vector:
arr = [C{:}]
这是完整的代码:
C = textread('test.txt', '%s', 'delimiter', '\n'); %// Read data
C = cellfun(@str2num, C, 'Uniform', false); %// Convert to numbers
C = cellfun(@(x)x(2:end), C, 'Uniform', false); %// Remove first values
arr = [C{:}]
arr =
1.0000 1.4000 1.7000 1.2000 1.5000 1.1000 1.1000 1.2000
这篇关于将数据块读入Matlab数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!