Converting location of a 2x3 vector into a matrix with value 1
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Wietze Zijpp
el 22 de Mzo. de 2022
Editada: Bruno Luong
el 23 de Mzo. de 2022
Suppose I have
a = 2×3
1 3
2 4
7 8
Now I want to create a matrix of dimension 10 x 10 where the entries 1,3 and 2,4 and 7,8 are equal to one.
Z = zeros(10) % 10 x 10 matrix containing only zeros
Z(a(1,1),a(1,2))=1 % now entry 1,3 is equal to 1
This is an illustrative example and I could for sure just code the second line three times. However for a large matrix a this will be tedious. I have tried to solve this problem with some for loops but without any positve result.
3 comentarios
Arif Hoq
el 23 de Mzo. de 2022
or this one ?
a = [1 3;2 4;7 8];
Z = zeros(10) ;% 10 x 10 matrix containing only zeros
Z(a(1,1),a(1,2))=1; % now entry 1,3 is equal to 1
Z(a(2,1),a(2,2))=1;
Z(a(3,1),a(3,2))=1
Respuesta aceptada
Más respuestas (3)
Stephen23
el 23 de Mzo. de 2022
Editada: Stephen23
el 23 de Mzo. de 2022
"However for a large matrix a this will be tedious."
If you have a large matrix it may be better if it were a sparse array (which can make operations using it more efficient), in which case this task is very easy:
a = [1,3;2,4;7,8];
m = sparse(a(:,1),a(:,2),1,10,10)
full(m) % checking
0 comentarios
Bruno Luong
el 23 de Mzo. de 2022
Editada: Bruno Luong
el 23 de Mzo. de 2022
a = [1,3;2,4;7,8]; % assumed there is no repeated indexes
A = accumarray(a,1,[10,10])
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!