How to generate a sparse matrix for a given array?
Mostrar comentarios más antiguos
Dear All,
I want to generate a sparse matrix B for a given array A. A contains two columns of indecis. For example,
A = [1 3;
1 4;
2 3;
2 5;
3 5;
4 5]
The sparse matrix B should be as follows:
B = [ 2 0 -1 -1 0;
0 2 -1 0 -1;
-1 -1 2 0 0;
-1 0 0 2 -1;
0 -1 -1 -1 3]
The characteristics of B:
- Sum of each row is zero.
- If we consider matrix A gives the information of edges of a graph, B(i,i) = sum of number of edges, B(i,j) = -1 if there is an edge between i and j.
Thanks a lot.
Benson
Respuesta aceptada
Más respuestas (1)
Here is one way:
A = [1 3;
1 4;
2 3;
2 5;
3 5;
4 5];
d = max(A(:));
B = sparse(A(:,1),A(:,2),-1,d,d) + sparse(A(:,2),A(:,1),-1,d,d);
for ii = 1:d
B(ii,ii) = -sum(B(ii,:));
end
disp(B)
7 comentarios
Benson Gou
el 24 de Mayo de 2021
A = [1 3;
1 4;
2 3;
2 5;
3 5;
4 5];
d = max(A(:));
B = sparse(A(:,1),A(:,2),-1,d,d) + sparse(A(:,2),A(:,1),-1,d,d);
% for ii = 1:d
% B(ii,ii) = -sum(B(ii,:));
% end
B = B - diag(sum(B,2));
disp(B)
Benson Gou
el 25 de Mayo de 2021
Bruno Luong
el 25 de Mayo de 2021
(1,28) -3
"There are 2 edges between 5 and 28."
Make it three.
Benson Gou
el 25 de Mayo de 2021
the cyclist
el 25 de Mayo de 2021
A=unique(sort(A,2),'rows')
is what you would need to do here as well.
If you posted a small example that exhibits the problem, it would help. But I'm guessing you have your answer.
Benson Gou
el 25 de Mayo de 2021
Categorías
Más información sobre Parametric Modeling en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!