从给定的具有不同长度的字符串数组中创建矩阵

时间:2015-10-08 09:25:50

标签: matlab matrix cell-array

我在细胞阵列中有3个序列:

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

 S1= 'ABCD' % which means A<B<C<D
 S2= 'ACD'  % which means A<C<D  % missing B in the full string of 'ABCD'
 S3= 'ABD'  % which means A<B<D  % missing C in the full string of 'ABCD'

我想将Input_cell中的每个字符串转换为矩阵Mi - by - j),这必须满足以下条件:

  • M(i,j)M(j,i)是随机的
  • M(i,i) = 0.5
  • M(i,j) + M(j,i) = 1
  • M(i,j) < M(j,i)例如A<B然后M(A,B) < M(B,A)

例如,如果我们有S1 = 'ABCD'(表示A<B<C<D),则M1矩阵的预期如下:

     A      B     C     D
 A  0.5    0.3   0.2   0.1 
 B  0.7    0.5    0    0.4
 C  0.8     1    0.5   0.1
 D  0.9    0.6   0.9   0.5

如果我们在S2 = 'ACD'的完整字符串中有A<C<D(表示B),但遗漏了'ABCD',我们会在每个0.5中加上值B M2在矩阵中的位置, A B C D A 0.5 0.5 0.2 0.1 B 0.5 0.5 0.5 0.5 C 0.8 0.5 0.5 0.1 D 0.9 0.5 0.9 0.5 矩阵的预期如下:

S3 = 'ABD'

如果我们在A<B<D的完整字符串中有C(表示'ABCD'),但遗漏了0.5,我们会在每个C中加上值M3 A B C D A 0.5 0.4 0.5 0.1 B 0.6 0.5 0.5 0.3 C 0.5 0.5 0.5 0.5 D 0.9 0.7 0.5 0.5 在矩阵中的位置,MediaPlayer mp = new MediaPlayer(); mp.setDataSource(context, notificationSoundUri); mp.setAudioStreamType(AudioManager.STREAM_ALARM); mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); mp.prepare(); 矩阵的预期如下:

seekTo(0)

如何从给定的序列单元格数组创建上述矩阵?

1 个答案:

答案 0 :(得分:1)

首先,您需要了解如何仅针对单个序列执行此操作:

  1. 0.51之间创建一个随机数字矩阵:

    M = 0.5*rand(4) + 0.5;
    
  2. 将主对角线设置为等于0.5

    M(logical(eye(4))) = 0.5;
    
  3. M的上三角设置为1 - 下三角形:

    M(triu(true(4))) = 1 - M(tril(true(4)));   %// Note the main diagonal doesn't matter...
    
  4. 找出缺少的字母,并相应地将行和列设置为0.5

    fullSeq = 'abcd';
    idx = find(fullSeq == setdiff(fullSeq, 'abd'));
    %// at this point you'll need to check if idx is empty first...
    M(:,idx) = 0.5;
    M(idx,:) = 0.5;
    
  5. 现在您可以为一个矩阵执行此操作,只需循环遍历单元格数组,或者将其封装到函数中并使用cellfun