How to quickly assign the values of a matrix using a given array?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Benson Gou
el 23 de Mayo de 2021
Comentada: DGM
el 24 de Mayo de 2021
Dear All,
I have an array A which contains two columns of integers. I want to build a matrix B in the following way.
For example,
A = [2 9; 1 5; 8 3]
The matrix B should be suilt as follows:
B = [0 1 0 0 0 0 0 0 -1 0; 1 0 0 0 -1 0 0 0 0 0; 0 0 -1 0 0 0 0 1 0 0]
How can I create matrix B for a goven A?
Thanks.
Benson
0 comentarios
Respuesta aceptada
DGM
el 23 de Mayo de 2021
Editada: DGM
el 23 de Mayo de 2021
Here is one way:
A = [2 9; 1 5; 8 3]
s = [size(A,1) 10]; % you're going to have to specify the output width
B = zeros(s);
B(sub2ind(s,(1:s(1)).',A(:,1))) = 1;
B(sub2ind(s,(1:s(1)).',A(:,2))) = -1;
B % show the result
2 comentarios
DGM
el 24 de Mayo de 2021
I really have no familiarity with handling sparse matrices or how to optimize for them. I'm sure someone else can though.
Más respuestas (1)
Walter Roberson
el 23 de Mayo de 2021
S = 10;
A = [2 9; 1 5; 8 3]
(A(:,1) == (1:S))-(A(:,2) == (1:S))
0 comentarios
Ver también
Categorías
Más información sobre Downloads en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!