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!