Reputation: 3784
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
Upvotes: 2
Views: 2390
Reputation: 21561
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.
Upvotes: 1
Reputation: 114936
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)
Upvotes: 7