sNooze
sNooze

Reputation: 39

R : Finding minimum value in a matrix

I want to iteratively sum the minimum value across different rows.

I have a matrix:

enter image description here

I would like to find the minimum value of this matrix by starting at row 1 (selected value not 0). Then iteratively, selecting the column that provides minimum value in row 1. Next, choose next row number which is the same number as the previously selected column and so on. Finally, sum the total numbers.

For example, start at row 1 and select column 4 because it provides the minimum value as 13.924. Then, moving to row 4 and finding the min value again which could be column 3 as 46.789. Then, moving to row 3 and finding the min value in this row which is in column 2 as 71.950. Then, from row 2, column 5 is selected.

For this example:

mat_test[1,4] + mat_test[4,3] + mat_test[3,2] + mat_test[2,1]

13.924 + 46.789 + 71.950 + 25.579

total sum = 158.242

Upvotes: 2

Views: 665

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

Assuming your matrix mat_test is always a square matrix, you may try the code below for your objective

mat_test <- `diag<-`(mat_test,Inf)
inds <- c()
row <- 1
while (!row %in% inds[,1]) {
  inds <- rbind(inds,c(row,rowNew <- which.min(mat_test[row,])))
  row <- rowNew
}
total <- sum(mat_test[inds])

Example

set.seed(1)
mat_test <- `diag<-`(matrix(rnorm(25),nrow = 5),0)

> mat_test
           [,1]       [,2]       [,3]        [,4]        [,5]
[1,]        Inf -0.8204684  1.5117812 -0.04493361  0.91897737
[2,]  0.1836433        Inf  0.3898432 -0.01619026  0.78213630
[3,] -0.8356286  0.7383247        Inf  0.94383621  0.07456498
[4,]  1.5952808  0.5757814 -2.2146999         Inf -1.98935170
[5,]  0.3295078 -0.3053884  1.1249309  0.59390132         Inf

then

> inds
     [,1] [,2]
[1,]    1    2
[2,]    2    4
[3,]    4    3
[4,]    3    1

and

> mat_test[inds]
[1] -0.82046838 -0.01619026 -2.21469989 -0.83562861

Upvotes: 1

Related Questions