2

私は位置行列を持っています:

positionMatrix = [1 2 3; 1 3 2; 2 1 3];

次のように配列を生成する単純な実装 (for ループなし) が必要です。

% there are 3 lines in positionMatrix, so it should generates 3 arrays of ones
array 1 should be [1 0 0; 0 1 0; 0 0 1] %from positionMatrix 1 2 3 
array 2 should be [1 0 0; 0 0 1; 0 1 0] %from positionMatrix 1 3 2
array 3 should be [0 1 0; 1 0 0; 0 0 1] %from positionMatrix 2 1 3

positionMatrix は M x N (M は N に等しくない) である可能性があります。

4

4 に答える 4

2

次の方法でも実行できますndgrid

positionMatrixTr = positionMatrix.';
[M N] = size(positionMatrixTr);
L = max(positionMatrixTr(:));
[jj kk] = ndgrid(1:M,1:N);
array = zeros(M,L,N);
array(sub2ind([M L N],jj(:),positionMatrixTr(:),kk(:))) = 1;

他の回答と同様に、これにより結果が 3D 配列になります。

于 2013-11-07T23:21:56.900 に答える
2

出力を単一の 3D 配列として生成する

 [M N] = size( positionMatrix );
 mx = max(positionMatrix(:)); % max column index
 out = zeros( [N mx M] );
 out( sub2ind( size(out), ...
         repmat( 1:N, [M 1] ),...
         positionMatrix, ...
         repmat( (1:M)', [1 N] ) ) ) = 1;
out(:,:,1) =
 1     0     0
 0     1     0
 0     0     1
out(:,:,2) =
 1     0     0
 0     0     1
 0     1     0
out(:,:,3) =
 0     1     0
 1     0     0
 0     0     1

各出力マトリックスを異なるセルとして使用する場合は、使用できますmat2cell

>> mat2cell( out, N, mx, ones(1,M) )
于 2013-11-07T16:02:41.527 に答える
-1

それがまさにあなたが必要としているものかどうかはわかりませんが、要件に近いものは次のとおりです。

positionMatrix = [1 2 3; 1 3 2; 2 1 3];

myArray = [positionMatrix == 1, positionMatrix == 2, positionMatrix == 3]   

これはもちろん、positionMatrix の行数は増加するが、列数は (あまり) 増加しないことを前提としています。

于 2013-11-07T16:00:41.517 に答える