2013-04-30 27 views
2

我有一個向量a = [1; 6; 8] 並且想要創建一個矩陣與n列和size(a,1)行。matlab - 創建矩陣與零行和一個索引

每個第i行都是零,但a(i)索引是1。

>> 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 

回答

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); 

如果你想有一個完整的矩陣只是使用

full(mat) 
1

這是我的第一個想法:

a = [1;6;8]; 
nCols = 10; 
nRows = length(a); 
M = zeros(nRows,nCols); 

M(:,a) = eye(nRows) 

基本上眼睛被分配到矩陣的右列。