I have MATLAB code that takes three long column vectors, d1, d2, and d3, and creates a band diagonal matrix from them. The code is basically this:
which produces the matrix F
and the vector tau
This isn't terribly memory efficient in this form, however, because for extremely long vectors, the matrix F takes up a lot of memory. So, in MATLAB, I used sparse matrices (specifically the -spdiags- function).
Now, I want to do something like this in Stata, but Mata doesn't have ANY sparse matrix capabilities at all, and the documentation recommends against using diag because, as in MATLAB, it's not memory-efficient.
Is there a memory-efficient way to replicate code like this in Mata? I have this code so far:
but without sparse matrices, I don't think this is memory efficient because it's going to store the entire matrix. When dealing with hundreds of thousands of observations, this Mata algorithm will fail because it can't allocate the memory for the full F matrix. Is there any way to replicate the behavior of sparse matrices in Mata so this code will actually work?
Code:
d1 = 1:5; d2 = 10:10:60; d3 = 100:100:700; F = diag(d1, -2) + diag(d2, -1) + diag(d3) + diag(d2, 1) + diag(d1, 2) y = [17 23 45 42 65 80 95]'; % random data, as a column vector tau = F \ y
Code:
F = 100 10 1 0 0 0 0 10 200 20 2 0 0 0 1 20 300 30 3 0 0 0 2 30 400 40 4 0 0 0 3 40 500 50 5 0 0 0 4 50 600 60 0 0 0 0 5 60 700
Code:
tau = 0.159379251059404 0.0928131665695312 0.133943228364286 0.0823548041069989 0.110248261684698 0.111056176436218 0.125407697293433
This isn't terribly memory efficient in this form, however, because for extremely long vectors, the matrix F takes up a lot of memory. So, in MATLAB, I used sparse matrices (specifically the -spdiags- function).
Now, I want to do something like this in Stata, but Mata doesn't have ANY sparse matrix capabilities at all, and the documentation recommends against using diag because, as in MATLAB, it's not memory-efficient.
Is there a memory-efficient way to replicate code like this in Mata? I have this code so far:
Code:
mata clear d1 = range(1, 5, 1); d2 = range(10, 60, 10); d3 = range(100, 700, 100); T = length(d3); F = diag(d3) for (i = 2; i <= T; i++) { F[i, i - 1] = d2[i - 1] F[i - 1, i] = d2[i - 1] } for (i = 3; i <= T; i++) { F[i, i - 2] = d1[i - 2] F[i - 2, i] = d1[i - 2] } y = (17 \ 23 \ 45 \ 42 \ 65 \ 80 \ 95); tau = svsolve(F, y);
Comment