字符串的单元格数组到矩阵

时间:2015-06-03 16:42:48

标签: string matlab matrix cell-array

$(document).on('change', 'input[type="checkbox"]', function(){
  //Your code
});

A = {'a','b','c','b','a',...} 是一个A单元格数组,我想从<1X400>创建一个矩阵,如果单元格为A,则矩阵显示为1,如果是a,它在矩阵中显示为2,在b显示为3。

谢谢。

3 个答案:

答案 0 :(得分:4)

具体案例

对于问题中列出的简单特定情况,您可以使用char将所有单元格元素转换为字符,然后从中减去96,其等同于{{1} } -

'a'-1

示例运行 -

A_numeric = char(A)-96

通用案例

对于一般的替换案例,你需要做更多的工作 -

>> A
A = 
    'a'    'b'    'c'    'b'    'a'
>> A_numeric = char(A)-96
A_numeric =
     1
     2
     3
     2
     1

示例输入 - 输出 -

%// Inputs
A = {'correct','boss','cat','boss','correct','cat'}
newcellval = {'correct','cat','boss'}
newnumval = [8,2,5]

[unqcell,~,idx]  = unique(A,'stable')
[~,newcell_idx,unqcell_idx] = intersect(newcellval,unqcell,'stable')
A_numeric = newnumval(changem(idx,newcell_idx,unqcell_idx))

答案 1 :(得分:2)

这很简单:

result = cell2mat(A)-'a'+1

对于字母与数字1,2,3 ......的通用关联:

letters2numbers = 'abc'; %// 'a'->1, 'b'->2 etc.
[~, result] = ismember(cell2mat(A), letters2numbers)

对于字符串与数字1,2,3 ......的通用关联:

strings2numbers = {'hi', 'hello', 'hey', 'good morning', 'howdy'};
A = {'hello', 'hi', 'hello', 'howdy', 'bye'};
[~, result] = ismember(A, strings2numbers)

在此示例中,

result =
     2     1     2     5     0 

答案 2 :(得分:1)

使用For循环,迭代A并将字符转换为数字

for loop = 1:length(A)
  outMat(loop) = char(A(loop)) - 96
end

我希望它有效。