Construct this matrix based on two vectors MATLAB

2019-02-26 02:01发布

问题:

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

i want to construct a matrix A such that A(1,2)=A(2,4)=A(4,6)=A(6,8)=A(8,10)=1 other elements 0.

please help

回答1:

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)


回答2:

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;


回答3:

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;