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

问题描述 投票:0回答:1

需要将存储为文本文件temp.dat中的两列十六进制值的数据读入具有8行和2列的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);

生成一个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代码基于“将文件内容读入数组”部分,大约是页面下方的三分之一。我引用的示例是做一些非常相似的事情,除了两列是一个int和一个float而不是两个字符。

在Redhat上运行Matlab R2017a。

以下是Azim提供的解决方案的完整代码,以及关于我发布问题后所学到的内容的评论。

fpath = './';
fname = 'temp.dat';
fid = fopen([fpath fname],'r');
formatSpec = '%9c\n';
% 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'
matlab
1个回答
0
投票

你的8x2 MATLAB变量很可能最终成为一个单元阵列。这可以分两步完成。

首先,你的行有9个字符,所以你可以使用formatSpec = '%9c\n'来读取每一行。接下来,您需要调整size参数以读取9行和8列; sizeA = [9 8]。这将把所有9个字符读入输出列;转置输出会让你更接近。

在第二步中,您需要将fscanf的结果转换为您的8x2单元阵列。既然您有R2017a,那么您可以使用cellstrsplit来获得结果。

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

© www.soinside.com 2019 - 2024. All rights reserved.