Hello. I am trying to create a new matrix in which each element is definied as the minimal value of the elements in the corresponding location from other matrices. I'm using Stata16, and My actual matrices contains roughly 35000 rows and 35000 collumms. For the examples here I define matrices A and B which are 3 X 3, and the result I'm looking for is matrix C
I know of two ways to approach this problem, one is working element by element, e.g:
This approach returns the desired result but is very expensive computationally. The other approach uses a logical condition to create the matrix, e.g:
This approach is more efficent, but dosen't handle cells with missing values (since 0 times a missing value equals missing value).
I'm looking for an approach that would be computationally efficent (since as mentioned above I'm working with large matrices), and would return the desired result even when encountering missing values. Would appreciate any advice.
Nir.
Code:
. mata : // Define matrices : A = (1 , 2 , . \ 4 , 5 , 6 \ . , 8 , 9) : B = (3 , 4 , 7 \ 2 , . , . \ 1 , 8 , 2) : C = (1 , 2 , 7 \ 2 , 5 , 6 \ 1 , 8 , 2) : : // Matrix A : A 1 2 3 +-------------+ 1 | 1 2 . | 2 | 4 5 6 | 3 | . 8 9 | +-------------+ : // Matrix B : B 1 2 3 +-------------+ 1 | 3 4 7 | 2 | 2 . . | 3 | 1 8 2 | +-------------+ : // Desired Matrix C : C 1 2 3 +-------------+ 1 | 1 2 7 | 2 | 2 5 6 | 3 | 1 8 2 | +-------------+ : end
Code:
. mata : C = A : for (i=1; i<=3; i++) { > for (j=1; j<=3; j++) { > if (B[i,j] < A[i,j]) (C[i,j] = B[i,j]) > } > } : C 1 2 3 +-------------+ 1 | 1 2 7 | 2 | 2 5 6 | 3 | 1 8 2 | +-------------+ : end
Code:
. mata : C = J(3,3,.) : C = A:* (A:<B) + B:* (B:<=A) : C 1 2 3 +-------------+ 1 | 1 2 . | 2 | 2 . . | 3 | . 8 2 | +-------------+ : end
I'm looking for an approach that would be computationally efficent (since as mentioned above I'm working with large matrices), and would return the desired result even when encountering missing values. Would appreciate any advice.
Nir.
Comment