matlab - 创建零行和一个索引的矩阵

mic*_*oo8 2 matlab matrix

我有一个向量,a = [1; 6; 8] 并希望创建一个包含n列和size(a,1)行的矩阵.

每个第i行都是零,但a(i)索引是一行.

>> make_the_matrix(a, 10)

ans = 
   1 0 0 0 0 0 0 0 0 0 0
   0 0 0 0 0 1 0 0 0 0 0
   0 0 0 0 0 0 0 1 0 0 0
Run Code Online (Sandbox Code Playgroud)

Sha*_*hai 7

使用 sparse

 numCol = 10; % number of colums in output matrix, should not be greater than max(a)
 mat = sparse( 1:numel(a), a, 1, numel(a), numCol );
Run Code Online (Sandbox Code Playgroud)

如果你想要一个完整的矩阵只是使用

 full(mat)
Run Code Online (Sandbox Code Playgroud)