Construct this matrix based on two vectors MATLAB

前端 未结 3 364
花落未央
花落未央 2021-01-22 02:22

I do have 2 vectors and i want to construct a matrix based onr and c

r =

 1
 2
 4
 6
 8

c =

 2
 4
 6
 8
10


        
相关标签:
3条回答
  • 2021-01-22 02:27

    First preallocate A to a zero matrix of appropriate size (given by the maximum values in r and c). Then, to address the desired entries, you need to convert to linear indexing, which you can do easily with sub2ind:

    A = zeros(max(r),max(c));
    A(sub2ind(size(A),r,c)) = 1;
    
    0 讨论(0)
  • 2021-01-22 02:41

    You could use the constructor for sparse matrices:

    full(sparse(r,c,1))
    

    by the way, if you want to apply this to large matrices with many zeros, stay with the sparse one. It uses much less memory for matrices with many zeros:

    sparse(r,c,1)
    
    0 讨论(0)
  • 2021-01-22 02:51

    You could use linear indexing to accomplish this.

    First, construct a matrix made out of zeros:

    A = zeros(max(r),max(c));
    

    Then set the elements to 1:

    A( size(A,1) * (c-1) + r ) = 1;
    
    0 讨论(0)
提交回复
热议问题