# Creating a matrix from data in a vector

조회 수: 9 (최근 30일)
Mark . 2013년 3월 11일
I have two vectors that contain positive integer values but are not consecutive. I would like to create a matrix that uses these values to place a 1 in a location. Example: I have a vector member_i = [1;1;2] and another vector member_j = [2;3;3]. I would like to create a matrix that is 2 times the number of rows of the vector and use that as the number of columns. I would also like to have the number of rows in the matrix equal 4 times the number of rows in the vectors. These vectors could be any length. I would also like to use the data from the vectors to put 1's in various locations, say for instance if member_i value is 1, the first row would have a 1 in row 1 column 1 and another 1 in row 2 column 2. Then if member_j value is 3, I would like row 3 column 5 to have a 1 and row 4 column 6 to have a 1. For the given vectors mentioned above the desired output would be:
DESIREDOUTPUT =
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
1 0 0 0 0 0
0 1 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
my current code:
Beta = zeros(4,2*member_count);
for idx5 = 1:member_count;
Beta(idx1,2*member_i(idx5,1)-1) = 1;
Beta(idx2,2*member_i(idx5,1)) = 1;
Beta(idx3,2*member_j(idx5,1)-1) = 1;
Beta(idx4,2*member_j(idx5,1)) = 1;
end
Beta =
1 0 1 0 0 0
0 1 0 1 0 0
0 0 1 0 1 0
0 0 0 1 0 1
1 0 1 0 0 0
0 1 0 1 0 0
0 0 1 0 1 0
0 0 0 1 0 1
1 0 1 0 0 0
0 1 0 1 0 0
0 0 1 0 1 0
0 0 0 1 0 1
Thanks for any help to this matlab noobie. Cedric Wannaz http://www.mathworks.com/matlabcentral/answers/contributors/1078046-cedric-wannaz was more than helpful to me before.
##### 댓글 수: 6이전 댓글 5개 표시이전 댓글 5개 숨기기
Matt J 2013년 3월 11일
편집: Matt J 님. 2013년 3월 11일
The picture does clarify things, and see my answer below. According to your rules, however, the number of columns will not be 2*length(member_i) as you originally posted. The number of columns would have to be (at least)
2*max([member_i;member_j])

댓글을 달려면 로그인하십시오.

### 채택된 답변

Matt J 2013년 3월 11일
n=length(member_i);
I=1:2*n;
J=I;
J(1:2:end)=member_i(:).';
J(2:2:end)=member_j(:).';
Beta=kron(sparse(I,J,1), eye(2));
##### 댓글 수: 1없음 표시없음 숨기기
Mark 2013년 3월 11일
Matt, thank you so much for your help. I will have to study this bit of code for awhile to understand exactly what's happening. I did a full(Beta) to check out what it looks like expanded. Works great.

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!