需要将存储为文本文件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'