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

后端 未结 3 1267
轮回少年
轮回少年 2021-01-18 11:52

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

相关标签:
3条回答
  • 2021-01-18 12:03

    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
    
    0 讨论(0)
  • 2021-01-18 12:08

    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

    0 讨论(0)
  • 2021-01-18 12:27

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

    M = v==1:4
    
    0 讨论(0)
提交回复
热议问题