Creating a matrix of logical arrays using an exsiting matrix

조회 수: 2 (최근 30일)
Tomer Marom
Tomer Marom 2021년 8월 29일
댓글: Tomer Marom 2021년 8월 30일
given a natural number n between 1 to 10, how do you create a logical array of size 10 where the n-th index has the value 1 ?
more accurately my problem is the following :
I have a column vector Y of size 5000 with values between 1 to 10 and I want to create a matrix of size 5000x10 where the i-th row is a logical array that has all zeros except for the n-th index, corresponding to the value of Y(i).
I wish to implement this vectorized only, no loops. How do I do this ?

채택된 답변

Wan Ji
Wan Ji 2021년 8월 29일
편집: Wan Ji 2021년 8월 29일
Use eye
num_labels = 10;
Y = [1;2;3;4;3;2;4;5;3;3;5;7;8]; % example Y
E =eye(num_labels)==1;
Your_matrix = E(Y,:)
Then
Your_matrix =
13×10 logical 数组
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
Or you can use sparse command
s = sparse(1:numel(Y),Y,true,numel(Y),num_labels);
Your_matrix = full(s)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Word games에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by