Access 2D matrix using 2 arrays of coords

hi, i'm having troubles working with indexes. Suppose i have this matrix (wich represent a 25x25):
matrix =
(4,6) -0.0000
(6,8) -1.0000
(2,9) -1.0000
(4,9) -1.0000
(2,10) -0.0000
(1,11) -0.0000
(5,11) -1.0000
(7,11) -1.0000
(4,12) -1.0000
(8,12) -0.0000
(3,13) -0.0000
(6,13) -0.0000
(7,13) -1.0000
(2,14) -0.0000
(11,14) -0.0000
(1,15) -1.0000
(3,15) -1.0000
(7,15) -0.0000
(9,16) -0.0000
(10,16) -1.0000
(2,17) -1.0000
(10,18) -1.0000
(17,18) -0.0000
(4,19) -0.0000
(16,19) -1.0000
(3,20) -1.0000
(8,21) -0.0000
(13,21) -1.0000
(20,21) -0.0000
(5,22) -0.0000
(14,22) -1.0000
(17,22) -0.0000
(6,23) -1.0000
(7,23) -0.0000
(9,23) -0.0000
(14,23) -1.0000
(12,24) -0.0000
(19,24) -1.0000
(1,25) -1.0000
(5,25) -0.0000
now let's say i want to create the diagonal as the sum of each row so that matrix[1][1] = sum(matrix(1,:)), matrix[2][2] = sum(matrix(2,:)) etc... problem is: I'm using an upper triangular matrix to act like a simmetric one ( space is of the essence). In this condition, the use of sum as before, takes only half the values i need to be added. My idea to work around this problem was to switch (i,j) -> (j,i) (wich outside of matlab would be a piece of cake), but had no luck with my trials so far.
the optimum will be something like:
for i=0 : rows_of_my_matrix
matrix[i][i] = sum(matrix(i,:)); %sums the [i][j] non zero elements of the row i in [i][i]
% something that sums the [i][j] non zero elements of the row i in [j][j]
end
can someone help my with this ? seems quite simple but i can't wrap my head around it (yes, i'm quite new to matlab)

Réponses (1)

Walter Roberson
Walter Roberson le 12 Sep 2015
for K = 1 : number_of_rows
total_right = sum(matrix(K,K:end));
total_left = sum(matrix(1:K-1,K));
matrix(K,K) = total_left + total_right;
end

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by