Creating a matrix of logical arrays using an exsiting matrix
1 回表示 (過去 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 ?
0 件のコメント
採用された回答
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 Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!