Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (50.2k points)

I want to fill the matrix with other matrix, is the below code correct?

pivot_simplex_fract<-function(matrice){

  n_row_matrix_2<-nrow(matrix_Standard) #number of the matrix

  n_col_matrix_2<-ncol(matrix_Standard)

  for (i in n_row_matrix_2){

    for (j in n_col_matrix_2) {

      matrix<-fractions(matrice[i,j])

    }

  }

  return(matrix)

}

1 Answer

0 votes
by (107k points)

See basically you are using the fractions function that has derived from the MASS packages which can work with matrices. But you don't really need to have a double loop. Let us say that you have a matrix as such:

X <- diag(5)/5

X

     [,1] [,2] [,3] [,4] [,5]

[1,]  0.2  0.0  0.0  0.0  0.0

[2,]  0.0  0.2  0.0  0.0  0.0

[3,]  0.0  0.0  0.2  0.0  0.0

[4,]  0.0  0.0  0.0  0.2  0.0

[5,]  0.0  0.0  0.0  0.0  0.2

You can also subset the rows and columns easily by the following code:

fractions(X)[1:3, 1:3]

     [,1] [,2] [,3]

[1,] 1/5    0    0 

[2,]   0  1/5    0 

[3,]   0    0  1/5

If you are a beginner ad want to know more about R the do check out the following R programming tutorial

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...