如何在 Matlab 中拆分一个单元格 1x1?

How to split a cell 1x1 in Matlab?

假设我有一个 1x1 单元格,其值为:'atcatcaaca'。 我的目标是:

  1. 在任何 'a' 旁边添加 1 到 5 'a'。

  2. 在任何 'c' 旁边添加 1 到 10 'c'。

  3. 在任何 'g' 旁边添加一个随机数 'g'。

  4. 在任何 't' 旁边添加一个随机数 't'。

    例如我有'atcatcaaca'。我的目标是让它像:'aaaattttcccaattttccaaaaaaaaaacccccccccaa'

我的想法是获取值单元格并将其以某种方式拆分为矩阵: 一个 |吨 |一个 |吨 | c |一个|一个| c |一种。 可能吗?如果可能,怎么办?

密码是:

filename = fullfile(matlabroot,'virus_nucleotitde2.dat');

Z = readtable(filename);

S = table2cell(Z);

num_rows = size (Z,1);
num_cols = size (Z,2);
for i=1:1:num_rows
   for j=1:1:num_cols
    B = S(i,j);
    a=0;
    c=0;
    g=0;
    t=0;


B{1} = num2cell(B{1});

n = randi(6);  % Random number between 1 and 6
B{1} = strrep(B{1} , 'a' , repmat('a' , 1, n));

n = randi(11);  % Random number between 1 and 11
B{1} = strrep(B{1} , 'c' , repmat('c' , 1, n));

n = randi(11); 
B{1} = strrep(B{1} , 'g' , repmat('g' , 1, n));

n = randi(11); 
B{1} = strrep(B{1} , 't' , repmat('t' , 1, n));

    end

end

已经这样了.. 'a string' 是一个字符数组,因此为了将它们转换为元胞数组,您需要使用通常的 num2cell 函数:

>> name_in_1x1_cell_array{1} = 'ataggatag'

name_in_1x1_cell_array = 

    'ataggatag'

>> name_in_1x1_cell_array{1} = num2cell(name_in_1x1_cell_array{1})

name_in_1x1_cell_array = 

    {1x9 cell}

你也可以直接访问字符,比如你可以循环显示一个字符串的每个字符:

name = 'some name';
for i = 1 : length(name)
  disp(name(i));
end

在单元格内,有一个 char,您可以使用大括号访问它:

 S = {'ataggatag'};
 B = S{1};
 disp(B)

那么,strrep是你的朋友:

n = randi(6);  % Random number between 1 and 6
B = strrep(B , 'a' , repmat('a' , 1, n));

n = randi(11);  % Random number between 1 and 11
B = strrep(B , 'c' , repmat('c' , 1, n));

n = randi(11); 
B = strrep(B , 'g' , repmat('g' , 1, n));

n = randi(11); 
B = strrep(B , 't' , repmat('t' , 1, n));

然后放回单元格

S{1} = B;
disp(S)

请注意,我使用 6 作为 'a' 的最大数量,因为 strrep 将替换原来的 a,而不是按照您的要求在其旁边添加字母。

编辑:

根据 OP 的编辑,这是您的解决方案:

S = {'ataggatag'};

num_rows = size (S,1);
num_cols = size (S,2);

for i=1:1:num_rows
   for j=1:1:num_cols
        n = randi(6);  % Random number between 1 and 6
        S{i,j} = strrep(S{i,j} , 'a' , repmat('a' , 1, n));

        n = randi(11);  % Random number between 1 and 11
        S{i,j} = strrep(S{i,j} , 'c' , repmat('c' , 1, n));

        n = randi(11); 
        S{i,j} = strrep(S{i,j} , 'g' , repmat('g' , 1, n));

        n = randi(11); 
        S{i,j} = strrep(S{i,j} , 't' , repmat('t' , 1, n));
    end

end

disp(S)

根据您的描述,而非代码:

使用函数 strrep 这很简单,因为它也对元胞数组进行操作:

cell_string = {'atcatcaaca'};

% add a's
cell_string = strrep(cell_string, 'a', repmat('a',1,5));

% add c's
cell_string = strrep(cell_string, 'c', repmat('c',1,10));

% add t's
cell_string = strrep(cell_string, 't', repmat('t',1,randi(10)));

函数repmat用于复制字符。