I have like a matrix in R and I want to get:
Max off - diagonal elements
Min off – diagonal elements
Mean off –diagonal elements
With diagonal I used max(diag(A)) , min(diag(A)) , mean(diag(A)) and worked just fine
But for off-diagonal I tried
dataD <- subset(A, V1!=V2)
Error in subset.matrix(A, V1 != V2) : object 'V1' not found
to use:
colMeans(dataD) # get the mean for columns
but I cannot get dataD b/c it says object 'V1' not found
Thanks!
In a table of numbers that has the same number of rows as columns, the entries that are not in the Main Diagonal are referred to as the off-diagonal entries in the table. In this example, all the 0s are in the off-diagonal cells.
This can be easily done by using sun function by extracting diagonal elements of the table using diag function. For example, if we have a table T then the sum of diagonal elements of T can be found as sum(diag(T)).
The off-diagonal elements ρij of the density matrix provide information about interference between the amplitudes of states ∣∣i〉 and ∣∣j〉, i.e., they represent the coherences in the mixed state. When a qubit is coupled to an environment, this coupling can cause some time dependence of elements of the density matrix.
If x is a matrix then diag(x) returns the diagonal of x . The resulting vector will have names if names is true and if the matrix x has matching column and rownames. The replacement form sets the diagonal of the matrix x to the given value(s).
In one simple line of code:
For a matrix A if you wish to find the Minimum, 1st Quartile, Median, Mean, 3rd Quartile and Maximum of the upper and lower off diagonals:
summary(c(A[upper.tri(A)],A[lower.tri(A)]))
.
Here the row()
and col()
helper functions are useful. Using @James A
, we can get the upper off-diagonal using this little trick:
> A[row(A) == (col(A) - 1)]
[1] 5 10 15
and the lower off diagonal via this:
> A[row(A) == (col(A) + 1)]
[1] 2 7 12
These can be generalised to give whatever diagonals you want:
> A[row(A) == (col(A) - 2)]
[1] 9 14
and don't require any subsetting.
Then it is a simple matter of calling whatever function you want on these values. E.g.:
> mean(A[row(A) == (col(A) - 1)])
[1] 10
If as per my comment you mean everything but the diagonal, then use
> diag(A) <- NA
> mean(A, na.rm = TRUE)
[1] 8.5
> max(A, na.rm = TRUE)
[1] 15
> # etc. using sum(A, na.rm = TRUE), min(A, na.rm = TRUE), etc..
So this doesn't get lost, Ben Bolker suggests (in the comments) that the above code block can be done more neatly using the row()
and col()
functions I mentioned above:
mean(A[row(A)!=col(A)])
min(A[row(A)!=col(A)])
max(A[row(A)!=col(A)])
sum(A[row(A)!=col(A)])
which is a nicer solution all round.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With