Bruno
Bruno

Reputation: 43

Adding non-zero elements of a matrix in R

I have a matrix 'w' with zero and non-zero elements. I want to print out the index of the non-zero elements in the matrix, print the values of each non-zero element and get the sum of the non-zero elements in the matrix. I know I can print the index of non-zero elements using

which(w!=0, arr.ind=TRUE)

I am trying to print the values of the non-zero elements in 'w' matrix but the code is returning the whole matrix instead of only the non-zero elements.

for(i in 1:36){
for(j in 1:36){
    if(w[i,j]!=0){
    print (w);
    }
    }
    }

I want to take out the non-zero elements in 'w' so that I can print the sum.

Upvotes: 0

Views: 381

Answers (1)

Kara Woo
Kara Woo

Reputation: 3615

To print the non-zero values:

w[w != 0]

To sum:

sum(w[w !=0 ])

ExperimenteR is of course correct that this will yield the same result as sum(w).

Upvotes: 3

Related Questions