Matlab fscanf 从文本文件中读取两列字符/十六进制数据



需要在文本文件 temp.dat 中以两列十六进制值的形式存储的数据读入具有 8 行和两列的 Matlab 变量。

想坚持使用FCSANF方法。

temp.dat 看起来像这样(8 行,两列(:

0000 7FFF
30FB 7641
5A82 5A82
7641 30FB
7FFF 0000
7641 CF05
5A82 A57E
30FB 89BF
% Matlab code
fpath = './';
fname = 'temp.dat';
fid = fopen([fpath fname],'r');
% Matlab treats hex a a character string
formatSpec = '%s %s';
% Want the output variable to be 8 rows two columns
sizeA = [8,2];
A = fscanf(fid,formatSpec,sizeA)
fclose(fid);

Matlab正在生产以下我意想不到的东西。

A = 8×8 字符数组

'03577753'
'00A6F6A0'
'0F84F48F'
'0B21F12B'
'77530CA8'
'F6A00F59'
'F48F007B'
'F12B05EF'

在另一种变体中,我尝试像这样更改格式字符串

formatSpec = '%4c %4c';

这产生了这个输出:

A =

8×10 字符数组

'0↵45 F7↵78'
'031A3F65E9'
'00↵80 4A↵B'
'0F52F0183F'
'7BA7B0C20 '
'F 86↵0F F '
'F724700AB '
'F6 1F↵55  '

还有另一个像这样的变体:

formatSpec = '%4c %4c';
sizeA = [8,16];
A = fscanf(fid,formatSpec);

生成一个 1 x 76 个字符的数组:

A =

'00007FFF
30FB 7641
5A82 5A827641 30FB
7FFF 0000
7641CF05
5A82 A57E
30FB 89BF'

希望并期望 Matlab 生成一个包含 8 行和 2 列的工作空间变量。

按照 Matlab 帮助区域的示例进行操作: https://www.mathworks.com/help/matlab/ref/fscanf.html

我的 Matlab 代码基于页面下方大约 1/3 的"将文件内容读取到数组中"部分。 我引用的示例正在执行非常相似的事情,只是两列是一个 int 和一个浮点数而不是两个字符。

在Redhat上运行Matlab R2017a。

这是Azim提供的解决方案的完整代码以及有关 我从发布问题中学到了什么。

fpath = './';
fname = 'temp.dat';
fid = fopen([fpath fname],'r');
formatSpec = '%9cn';
% specify the output size as the input transposed, NOT the input.
sizeA = [9,8];
A = fscanf(fid,formatSpec,sizeA);
% A' is an 8 by 9 character array, which is the goal matrix size.
% B is an 8 by 1 cell array, each member has this format 'dead beef'.
%
% Cell arrays are data types with indexed data containers called cells, 
%  where each cell can contain any type of data.
B = cellstr(A');
% split divides str at whitespace characters.
S = split(C)
fclose(fid)

S =

8×2 电池阵列

'0000'    '7FFF'
'30FB'    '7641'
'5A82'    '5A82'
'7641'    '30FB'
'7FFF'    '0000'
'7641'    'CF05'
'5A82'    'A57E'
'30FB'    '89BF'

您的 8x2 MATLAB 变量很可能最终会成为一个单元数组。这可以通过两个步骤完成。

首先,您的行有 9 个字符,因此您可以使用formatSpec = '%9cn'来阅读每一行。接下来您需要调整大小参数以读取 9 行和 8 列;sizeA = [9 8].这会将所有 9 个字符读入输出的列;转置输出将使您更接近。

在第二步中,您需要将fscanf的结果转换为 8x2 单元格数组。由于您有 R2017a,因此您可以使用cellstrsplit来获得结果。

最后,如果您需要每个十六进制值的整数值,则可以在单元格数组中的每个单元格上使用hex2dec

最新更新