Creating an m by n matrix of 0s and 1s from m-sized vector of column indexes

我怕爱的太早我们不能终老 提交于 2019-12-19 19:12:21

问题


I have a m-dimensional vector of integers ranging from 1 to n. These integers are column indexes for m × n matrix.

I want to create a m × n matrix of 0s and 1s, where in m-th row there's a 1 in the column that is specified by m-th value in my vector.

Example:

% my vector (3-dimensional, values from 1 to 4):
v = [4;
     1;
     2];

% corresponding 3 × 4 matrix
M = [0 0 0 1;
     1 0 0 0;
     0 1 0 0];

Is this possible without a for-loop?


回答1:


Of course, that's why they invented sparse matrices:

>> M = sparse(1:length(v),v,ones(length(v),1))
M =

   (2,1)        1
   (3,2)        1
   (1,4)        1

which you can convert to a full matrix if you want with full:

>> full(M)
ans =

     0     0     0     1
     1     0     0     0
     0     1     0     0



回答2:


Or without sparse matrix:

>> M = zeros(max(v),length(v));
>> M(v'+[0:size(M,2)-1]*size(M,1)) = 1;
>> M = M'

M =

 0     0     0     1
 1     0     0     0
 0     1     0     0

Transposition is used because in matlab arrays are addressed by columns




回答3:


In Octave, at least as of 3.6.3, you can do this easily using broadcasting:

M = v==1:4


来源:https://stackoverflow.com/questions/10665179/creating-an-m-by-n-matrix-of-0s-and-1s-from-m-sized-vector-of-column-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!