如何在Matlab中读取具有可变十六进制值列的文本文件? [英] How do I read a text file with variable hexadecimal value columns in matlab?

查看:384
本文介绍了如何在Matlab中读取具有可变十六进制值列的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当大的文本文件(超过16,000行),其格式如下:

I have a rather large text file (over 16,000 lines) that has the following format:

#ID     #Line Num       #Var Col Length Values (HEX):
45      00001           FFFF FFFF 0000 0000
45      00002           0000 0000 FFFF FFFF
47      00003           AAAA 1111 AAAA 1111 AAAA 1111
49      00004           BBBB 2222 

注意:这显然是由数据组成,因为实际文件中有更多的十六进制值.

在Matlab中,我尝试使用单行的textscan命令:

In Matlab I tried using the textscan command of a single line:

fp = fopen(filePath, 'rt');
readLine = fgetl(fp);
[ignored, pos] = textscan(readLine, '%d');
values = textscan(readLine(pos+1:end), '%x');

我收到格式错误的字符串错误.我假设textscan不支持十六进制值的转换.我也尝试过在这里找到的解决方案:

I get an error of a badly formatted string. I'm assuming that textscan doesn't support conversion of hex values. I've also tried the solution found here:

将十六进制数据加载到MATLAB中的问题(错误?)

,但这似乎也不起作用.我试图避免分别转换每个十六进制值(某种程度上,我现在已经实现了此解决方案),因为这需要很长时间才能完成.如何从文本文件中扫描/解析可变列宽的十六进制值?

but that also doesn't seem to work as well. I'm trying to avoid converting each Hex Value individually (somewhat the solution I have implemented now) as this takes a very long time to do. How do I scan/parse variable column width hexadecimal values from a text file?

推荐答案

您可以使用以下方法将文本文件读入字符串的单元格数组,并使用regexp将其拆分为单独的值:

You can use the following approach read the text file into a cell array of strings and split it into separate values using regexp:

fp = fopen(filePath, 'rt');
C = textscan(fp, '%s', 'CommentStyle', '#', 'Delimiter', '');
C = regexp(C{:}, '\w+', 'match');
fclose(fp);

这将产生一个单元格数组,例如,您的示例将如下所示:

This should yield a cell array of cell arrays that, for your example, would look like this:

C =
    {'45'    '00001'    'FFFF'    'FFFF'    '0000'    '0000'}
    {'45'    '00002'    '0000'    '0000'    'FFFF'    'FFFF'}
    {'47'    '00003'    'AAAA'    '1111'    'AAAA'    '1111'    'AAAA'    '1111'}
    {'49'    '00004'    'BBBB'    '2222'}

您可以根据自己的喜好操纵所得的单元阵列.例如,丢弃每一行的前两列,然后将所有内容都转换为十进制:

You can manipulate the resulting cell array to your liking. For instance, discard the first two columns in each row, and convert everything to decimal:

result = cellfun(@(x)hex2dec(x(3:end)), C, 'UniformOutput', false)

这篇关于如何在Matlab中读取具有可变十六进制值列的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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