Search code examples
matlabloopsmatrixcell-arraydimension

Create matrices from strings in a cell-array


I have a string S1='ACD'. I generate the matrix based on the S1 as follows:

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

The output is OK:

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

Now, I would like to use a loop though the cell-array input-cell to generate 3 matrices (based on the above code) of the 3 strings in the cell-array as follows:

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

The error is :

 Error using  == Matrix dimensions must agree.

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

How can I fix this problem to generate 3 matrices? Or any other solutions instead of using "for loop" ?


Solution

  • Try changing

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

    to this:

    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
    

    But also, you realise that you are just overwriting M at each iteration and never actually storing the past results right?