2

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」のみであり、3 番目の列はすべてのセルの最終行で「1」です。

すなわち:P{1}= 100;010;000;000;001

どうすればいいですか?

私が今まで作ってきたものから:

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

どうすればそれらをセルに入れることができますか?

どうもありがとうございます

4

1 に答える 1

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

論理行列の配列が必要な場合は、2 行目zerosを次のように置き換えます。false

P = repmat({false(5,3)},1,n);
于 2012-02-09T15:42:25.437 に答える