将单元格数组中的字符串替换为1x3数字单元格数组

时间:2011-07-01 15:58:56

标签: matlab

单元格数据如下:

data=

'A' [0.006] 'B'
'C' [3.443] 'C'

我想将第一列中的字符转换为1x3向量,表示

  • 'A'替换​​为[0] [0] [0],
  • 'C'替换为[0] [1] [0] ..

结果将是

[0] [0] [0] [0.006] 'B'
[0] [1] [0] [3.443] 'C'

我尝试的代码如下:

B=data(1:end,1);
B=regexprep(B,'C','[0 0 0]');
B=regexprep(B,'A','[0 1 0]');

结果显示我

B=

'[0 0 0]'
'[0 1 0]'

这是错误的,每个字符都不会更改为1x3数组...请帮助...

1 个答案:

答案 0 :(得分:0)

由于您未指定将字母转换为数字的规则, 我假设您要将A替换为000B替换为001,...,H替换为111 (即二进制数字0到7,对应字母A到H)。

如果您想要升级到Z,可以轻松更改以下代码。

%# you data cell array
data = {
    'A' [0.006] 'B'
    'C' [3.443] 'C'
};

%# compute binary numbers equivalent to letters A to H
binary = num2cell(dec2bin(0:7)-'0');      %# use 0:25 to go up to Z

%# convert letters in to row indices in the above cell array "binary"
idx = cellfun(@(c) c-'A'+1, upper(data(:,1)));

%# replace first column, and build new data
newData = [binary(idx,:) data(:,2:end)]

结果:

newData = 
    [0]    [0]    [0]    [0.006]    'B'
    [0]    [1]    [0]    [3.443]    'C'