从单元格数组中的字符串创建矩阵

时间:2015-10-12 14:30:09

标签: matlab loops matrix cell-array dimension

我有一个字符串S1='ACD'。我根据S1生成矩阵如下:

fullSeq = 'ABCD';
idx = find(fullSeq == setdiff(fullSeq, 'ACD')); % it is OK 
M(:,idx) = 0.5
M(idx,:) = 0.5
M(logical(eye(4))) = 0.5

输出正常:

M =

0.5000    0.5000    0.2003    0.3279
0.5000    0.5000    0.5000    0.5000
0.8298    0.5000    0.5000    0.2452
0.7997    0.5000    0.7548    0.5000

现在,我想通过单元阵列输入单元使用一个循环来生成单元数组中3个字符串的3个矩阵(基于上面的代码),如下所示:

input_cell= {'ABCD','ACD', 'ABD'}


for i=1:numel(input_cell)



    M = 0.5*rand(4) + 0.5;

    M(triu(true(4))) = 1 - M(tril(true(4)));   

    fullSeq = 'ABCD';
    idx = find(fullSeq == setdiff(fullSeq, input_cell{i} )); % something wrong here

     M(:,idx) = 0.5
     M(idx,:) = 0.5
     M(logical(eye(4))) = 0.5

end

错误是:

 Error using  == Matrix dimensions must agree.

 Error in datagenerator (line 22)
 idx = find(fullSeq == setdiff(fullSeq, input_cell{i} ));   

如何解决此问题以生成3个矩阵?或者任何其他解决方案,而不是使用“for循环”?

1 个答案:

答案 0 :(得分:1)

尝试更改

fullSeq = 'ABCD';
idx = find(fullSeq == setdiff(fullSeq, input_cell{i} )); % something wrong here
...

到此:

fullSeq = 'ABCD';
letter = setdiff(fullSeq, input_cell{i})
if isempty(letter)
    idx = find(fullSeq == letter);
    M(:,idx) = 0.5
    M(idx,:) = 0.5
end
M(logical(eye(4))) = 0.5

但是,你也意识到你只是在每次迭代时覆盖M并且从未真正存储过去的结果吗?