2
votes

i have a vector a = [1; 6; 8] and want to create a matrix with n columns and size(a,1) rows.

Each i'th row is all zeros but on the a(i) index is one.

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

2 Answers

7
votes

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

if you want a full matrix just use

 full(mat)
1
votes

Here is my first thought:

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

M(:,a) = eye(nRows)

Basically the eye is assigned to the right columns of the matrix.