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 Center および File ExchangeWord games についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by