Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract two matrices in r

Tags:

r

matrix

I have created two matrices as followings:

    A = c(1,2,3)
    B = c(2,4,6)
    c = as.matrix(c(3,6,9))

    z = as.matrix(cbind(A, B))

Now I want to take the matrix c and subtract it row by row e.g. 1-3 = -2 & 2-3 =-1 Do get a good understanding of R programming, I would like to create a for loop. PLEASE ALL YOUR ANSWERS SHOULD IMPROVE MY FOR LOOP.

 for (i in 1:nrow(z))# for the rows in matrix z
  for (j in 1:nrow(c)) # for the rows in matrix c 
     {
      sub = matrix(NA, 3,2) # make a placeholder 
      sub [i,]= z[i,]-c[j,] # i am not sure whether this right
      return((sub))
   }

I get the following error:

    Error: no function to return from, jumping to top level

I believe my for loop is wrong, can anyone help. The purpose is to learn more about R programming. Thanks

like image 709
Boro Dega Avatar asked Feb 05 '26 12:02

Boro Dega


1 Answers

This is a good case for sweep:

sweep(z, 1, c)
#      A  B
#[1,] -2 -1
#[2,] -4 -2
#[3,] -6 -3
like image 88
Pierre L Avatar answered Feb 07 '26 01:02

Pierre L