ana_gg
ana_gg

Reputation: 370

Matrix multiplication with vector based on another matrix in R

I need to multiply one matrix with one conditional vector, to get a vector of solutions, based on another matrix.

# Matrix A
lsA <- c(1,1,0,1,1,2,1,0,1,2,1,1,0,0,1,1,0,0,0,1)
A <- matrix(lsA,4,5, byrow = T)

# Matrix B
ls <- c("10","11","01","10","01","00","11","01","11","10","10","11","00","12","12","02","22","02","03","11")
B <- matrix(ls,4,5, byrow = T)

a1 <- c(0.128, 0.130, 0.280, 0.500, 0.650)
a2 <- c(0.055, 0.120, 0.250, 0.430, 0.600)

M1 = A%*%a1
M2 = A%*%a2

M3 <- NULL
for(i in 1:nrow(A)){
  if(B[[i]]=='00' | B[[i]]=='01' | B[[i]]=='10' | B[[i]]=='11'){
    M3[[i]] <- colSums(A[,i]*a1[i]) 
  } else {
    M3[[i]] <- colSums(A[,i]*a2[i]) 
  }

The code for M3 is not working... So I want to have a vector as M1 or M2, but the elements of the matrix A should be multiplied by one or the other vector, based on the codes of B.

Any ideas?

Upvotes: 2

Views: 94

Answers (2)

ana_gg
ana_gg

Reputation: 370

Here is the solution. Now the loop is iterating over every element both column and row-wise, so it is making the multiplication element by element:

 M3 <- matrix(,4,5)
 for(i in 1:nrow(A)){
   for (j in 1:ncol(A))
   if(B[i,j]=='00' | B[i,j]=='01' | B[i,j]=='10' | B[i,j]=='11'){
     M3[i,j] <- A[i,j]*a1[j] 
   } else {
     M3[i,j] <- A[i,j]*a2[j] 
   }
 }
 M3 = rowSums(M3); M3

Upvotes: 0

akrun
akrun

Reputation: 887153

The issue is A[, i] drops the dimensions and return a vector. We need drop = FALSE and as we are using colSums, the input object is without a dimensions here i.e. ?colSums

x- an array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data frame. For .colSums() etc, a numeric, integer or logical matrix (or vector of length m * n).

for(i in 1:nrow(A)){
   if('00' %in% B[,i] | '01' %in% B[,i] | '10' %in% B[, i] | '11' %in% B[,i]){
    M3[[i]] <- colSums(A[,i, drop = FALSE]*a1[i]) 
  } else {
    M3[[i]] <- colSums(A[,i, drop = FALSE]*a2[i]) 
  }
}

-output

> M3
[[1]]
[1] 0.64

[[2]]
[1] 0.39

[[3]]
[1] 0

[[4]]
[1] 0.86

Upvotes: 3

Related Questions