I'm trying to convert some code from MATLAB to R.
I'm having particular problems converting this part of a differential equation:
In MATLAB :
dA.*(A*N - N.*sum(A,2))
where dA is an integer, A is a 10x10 matrix and N is a 10x1 matrix (see example code below)
In R so far I've got this:
dA*(A*N - N*colSums(A))
but for some reason it doesn't seem to be giving the same result. Does anyone have any ideas as to what I've done wrong?
Example of the data I'm using below:
in MATLAB:
dA = 0.1;
N = 120000*ones(1,nN);
seq = [0 1 0 0 0 1 0];
seq2 = repmat(seq,1,20);
seq100 = seq2(1:100)
A = AA-diag(diag(AA));
in R:
dA <- 0.1
N <- c(120000, 120000, 120000, 120000, 120000, 120000, 120000, 120000, 120000, 120000)
num_zeros_int <- zeros(70, 1)
num_ones_int <- ones(30, 1)
seq <- c(0,1,0,0,0,1,0)
seq2<- rep(seq, times = 20)
seq100 <- seq2[0:100]
int_mat <- matrix(seq100, nests, nests)
Matlab expression:
dA.*(A*N - N.*sum(A,2))
where
dA: real number
A: 10 x 10 matrix
N: 10 X 1 matrix
A*N: matrix multiplication
sum(A,2): sum of rows in A (10x1 matrix)
N.*sum(A,2): element by element multiplication (10 x 1 matrix)
Let's set up the following example in R:
A = matrix(data = 1:100,nrow = 10)
N = matrix(data = 1:10)
dA = 0.1
> A
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
> N
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
The first term is:
z1 = A %*% N
And the second term:
srow = rowSums(A)
z2 = srow * N
Which leads to the final result:
result = dA * (z1-z2)
Final equation
result = dA * (A %*% N - rowSums(A)*N)
This should give you the same answer as Matlab's dA.*(A*N - N.*sum(A,2))