Azzera filtri
Azzera filtri

Creating a matrix of logical arrays using an exsiting matrix

1 visualizzazione (ultimi 30 giorni)
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 ?

Risposta accettata

Wan Ji
Wan Ji il 29 Ago 2021
Modificato: Wan Ji il 29 Ago 2021
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)

Più risposte (0)

Categorie

Scopri di più su Word games in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by