在 MATLAB 中的数组中插入十六进制值

Insert hexadecimal values in array in MATLAB

我是 matlab 的新手。我想像这样在数组中存储十六进制值

P=[0x96,0x97,0x98];

但是我在网上冲浪 google 我没有找到解决方案 所以首先我将这个十六进制转换为十进制所以我得到了这样的数组

P=[150,151,152];

现在我正在尝试获取 P 数组值的十六进制值。

我试过了

P=[dec2hex(150),dec2hex(151),dec2hex(152)];

但是当我尝试打印 P(1) 时,我得到的不是 96,而是 9。我不理解这部分。我怎样才能得到正确的结果?请帮助我。

参见 dec2hex

的手册
dec2hex - Convert decimal to hexadecimal number in string

你得到的是 string,因此 P(1) 只给你字符串的第一个字符。

试试这样的:

>> P=[dec2hex(150);dec2hex(151);dec2hex(152)]; % note the ; instead of ,
>> P

P =

96
97
98

>> P(1,:)

ans =

96

但是,P仍然是一个字符数组。

Matlab 将十六进制数存储为字符数组(或字符串)。

所以

a = dec2hex(150)

returns:

a = '96'

像您一样连接十六进制字符串:

P=[dec2hex(150),dec2hex(151),dec2hex(152)]

returns:

P = '969798'

因此,P(1) = '9'

您可能想使用元胞数组来单独存储十六进制数:

P = {dec2hex(150),dec2hex(151),dec2hex(152)};
P{1}

returns:

P = '96'

要检索数值,请使用

hex2dec(P{1})

您可以使用 arrayfundec2hex 对它们进行元素处理,并生成一个元胞数组作为使用格式 0x... -

的输出
P=[150,151,152] %// Input array
out = arrayfun(@(n) strcat('0x',dec2hex(P(n))),1:numel(P),'Uni',0)

代码运行-

out = 
    '0x96'    '0x97'    '0x98'