Matlab-读取不规则文本文件 [英] Matlab- Reading irregular textfile

查看:535
本文介绍了Matlab-读取不规则文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在matlab中读取包含以下文本的文本文件?

How can I read a textfile containing the following text in matlab?

B4070IC05.tif,11
B4070IC06.tif,11,15,16,6,7 
B4070IC07.tif,13,14,4,18,9
B4070IC08.tif,10,7
B4070IC09.tif,4,22,7
B4070IC10.tif,14,15,19,20,24,29,9
B4070IC11.tif,10,11,20,21
B4070IC12.tif,13,14,5,9

我不知道文本的列数.

有没有办法将这些数据放入单元矩阵?加载数据后如何打印单元格矩阵?

Is there a way to put these data in a cell matrix? how can I print the cell matrix after the data load?

推荐答案

您可以为此使用textscan.确保%f -s的数量足够长以覆盖文件中最长的一系列值.如果所有数值都是整数,则还可以使用实例%d"(请参见文字扫描以获取更多详细信息).

You can use textscan for this. Make sure that the number of %f-s is long enough to cover the longest series of values in your file. If all numeric values are integer, you could also use for instance `%d' (see textscan for more details).

fid = fopen(filename);
A = textscan(fid,'%s %f %f %f %f %f %f %f','delimiter',',');
fclose(fid);

结果是一个单元格数组,第一列为字符串'blabla.tif',第二列为最后一列为数值.如果文件中没有值,则该值等于NaN.

The result is a cell array, with the first column the strings 'blabla.tif' and the second up to last column the numeric values. If a value is not present in the file, it equals NaN.

通过A{i}(j)访问第i列的第j个值.

Accessing the j-th value of the i-th column is done by A{i}(j).

顺便说一句,文件的最后一行不像其他行一样附加NaN.这意味着将结果直接组合到单元格数组中是不可能的:最后几个数组(可能)比第一个数组短.我没有找到明显的解决方案,因此我们必须手动执行此操作:

By the way, the last line in the file is not appended with NaNs, like the other lines. This means that combining the result into a cell array is not directly possible: the last few arrays are (might be) shorter than the first. I did not find an obvious fix for that, so we have to do that manually:

idx = find(diff(arrayfun(@(idx)numel(A{idx}),1:numel(A))));
cA = [A{1} num2cell([horzcat(A{2:idx}) [horzcat(A{idx+1:end});nan(1,numel(A)-idx)]])];

这篇关于Matlab-读取不规则文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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