0

How can I divide each elements of rows of a symmetric matrix NxN by a column vector (Nx1), such that I can obtain not a Nx1 vector but again a symmetric matrix NxN, where each elements along the rows are divided by the correspiding elements of the column vector? here the matrix:

   In1   In2    In3     In4
In1 0           
In2 0     0     
In3 0,125 0,125 0   
In4 0     0     0,125   0

here the column vector:

0,125
0,25
0,625
0,25

here the final matrix after the division:

    In1 In2 In3 In4
In1 0           
In2 0   0       
In3 0,2 0,2 0   
In4 0   0   0,5 0

Thanks in advance for your help!

Leonardo
  • 71
  • 1
  • 1
  • 10

2 Answers2

0

Here's a route via a tbl (data frame) since it makes it amenable to mapping through columns, and because read_table2 is better than manually typing data (please provide data in a reproducible format!). The last two lines are just to coerce back to the requested matrix form.

library(tidyverse)
tbl <- read_table2(
  "In1   In2    In3     In4
0           
0     0     
0.125 0.125 0   
0     0     0.125   0"
)
#> Warning: 2 parsing failures.
#> row # A tibble: 2 x 5 col     row col   expected  actual    file         expected   <int> <chr> <chr>     <chr>     <chr>        actual 1     1 <NA>  4 columns 2 columns literal data file 2     2 <NA>  4 columns 3 columns literal data

vec <- c(0.125, 0.25, 0.625, 0.25)

tbl %>%
  map_dfc(~ . / vec) %>%
  as.matrix() %>%
  `rownames<-`(colnames(.))
#>     In1 In2 In3 In4
#> In1 0.0  NA  NA  NA
#> In2 0.0 0.0  NA  NA
#> In3 0.2 0.2 0.0  NA
#> In4 0.0 0.0 0.5   0

Created on 2018-03-13 by the reprex package (v0.2.0).

Calum You
  • 14,687
  • 4
  • 23
  • 42
0

Transpose the matrix, multiply it by a diagonal matrix whose entries are the reciprocals of the entries in your column vector, and then transpose the result.

x <- matrix(1:16, 4)
v <- c(1:4)
t(t(x) %*% diag(1 / v))    v <- c(1:4)
t(t(x) %*% diag(1 / v))
ebohlman
  • 14,795
  • 5
  • 33
  • 35