【问题标题】:producing cell array生产单元阵列
【发布时间】:2012-02-09 07:18:51
【问题描述】:

我想在matlab中生成一个单元格数组,如下所示:

P=  {100;010;000;000;001}  
    {100;000;010;000;001} 
    {100;000;000;010;001} 
    {000;100;010;000;001} 
    {000;100;000;010;001} 
    {000;000;100;010;001}

在哪里P= {5x3 cell} {5x3 cell} {5x3 cell} {5x3 cell} {5x3 cell} {5x3 cell};

从 5x3 矩阵中,每列中的模式应该只有一个“1”,每个单元格的最后一行的第三列是“1”。

即:P{1}= 100;010;000;000;001

我该怎么做?

从我一直编到现在:

PP=zeros(5,3);
P={1,6};
P={PP,PP,PP,PP,PP,PP};

如何将它们放入单元格中?

非常感谢

【问题讨论】:

    标签: matlab cell-array


    【解决方案1】:

    试试这个:

    x = unique(perms([0 0 2 4]),'rows'); %# we'll convert 2 to 10 and 4 to 100 later
    xi = randperm(size(x,1)); %# permute rows randomly
    n = 6;
    xi = xi(1:n); %# k random rows
    x = x(xi,:);
    x = [ x ones(n,1) ]'; %# add 1s and transpose
    %# convert to strings representing binary numbers, then to cell array
    out = reshape(cellstr(dec2bin(x)), size(x,1), n);
    %# split the cell array by columns
    out = mat2cell(out, size(out,1), ones(1,n));
    

    如果你真的需要数字(0、10、100),而不是字符串,代码会短一点:

    x = unique(perms([0 0 10 100]),'rows');
    xi = randperm(size(x,1));
    n = 6;
    xi = xi(1:n);
    x = x(xi,:);
    x = [x ones(n,1)]';
    out = mat2cell(x,size(x,1),ones(1,n));
    

    更新

    根据您的评论,这是新代码:

    n = 6;
    P = repmat({zeros(5,3)},1,n); %# output array preallocation
    
    x = unique(perms([0 0 1 2]),'rows');
    xi = randperm(size(x,1));
    xi = xi(1:n);
    x = x(xi,:);
    
    c = [x ones(n,1)+2]'; %# column index
    r = repmat((1:5)',1,n); %# row index
    for k=1:n
        P{k}(sub2ind( [5 3], r(c(:,k)>0,k), c(c(:,k)>0,k) )) = 1;
    end
    

    如果您需要逻辑矩阵数组,只需将第二行中的 zeros 替换为 false

    P = repmat({false(5,3)},1,n);
    

    【讨论】:

    • 谢谢。我需要它们是二进制的,每列只有一个“一”。行组合如下:1&2;1&3;1&4;2&3;2&4;3&4; P=[5x3][5x3][5x3][5x3][5x3][5x3] 其中 P{1} = (第 1&2 行的组合) 1 0 0; 0 1 0; 0 0 0; 0 0 0; 0 0 1; P{2}= (第 1&3 行的组合) 1 0 0; 0 0 0; 0 1 0; 0 0 0; 0 0 1; P{6}= 0 0 0; 0 0 0; 1 0 0; 0 1 0; 0 0 1;
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 2014-06-13
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多