# Create Compiled Function - Matrix Initialization

I am attempting to compile the following function:

But I receive the following error messages:

How should I initialize the matrix Vw to enable the assignment to Vw[[1,1]]?

cKalmanIterateInit = Compile[{{data, _Real, 2}, {cointwgts, _Real, 2}, {bb, _Real,
2}, {bm, _Real, 2}, {cCovb, _Real, 2}} ,
Module[{b = bb, Covb = cCovb, X, Y, Yport, Yhat, k, n, i, a, G,
w, Vw, e, Ve},
{k, n} = Dimensions@data; Vw = Table[0., {k}, {k}];
Y = data[[1]];
Yport = cointwgts.data;
X = data;
X[[1, All]] = 1;
Yhat = Total[b*X];
a = IdentityMatrix[k];
a[[1, 1]] =
Max[-1.0,
Min[1.0, (b[[1,
2 ;; n]].b[[1, ;; (n - 1)]])/(b[[1, ;; (n -
1)]].b[[1, ;; (n - 1)]])]];
G = b.\!$$TraditionalForm\\*SuperscriptBox[\(b$$, $$\[Transpose]$$]\)/n; Covb[[1]] =
DiagonalMatrix@Diagonal[(b - bm).Transpose[b - bm]/(n - 1)];
w = b[[All, 2 ;; n]] - a.b[[All, ;; (n - 1)]];
Vw = DiagonalMatrix@Diagonal[w.\!$$TraditionalForm\\*SuperscriptBox[\(w$$, $$\[Transpose]$$]\)]/(n - 1);
Vw[[1, 1]] = (1 - a[[1, 1]]^2)*G[[1, 1]];
e = Y - Yhat;  (* measurment prediction error *)
Ve = e.e/n;        (* measurement error variance  *)
b[[All, 1]] = Join[{0}, -cointwgts[[2 ;; k]]]/cointwgts[[1]];
{Y, X, a, b, bm, Ve, Vw, Covb}], {{Covb, _Real, 3}},
Parallelization -> True, CompilationTarget -> "C"]


Compile::cset: Variable Vw of type {_Real,2} encountered in assignment of type {_Real,0}.

• One can initialize as Vw = Table[0., {m}, {n}] with suitable m and n and fill the matrix afterwards. Since I don't have your code in copyable code, I won't try. – Henrik Schumacher Jan 14 '19 at 17:38
• Thank you! I was trying to post the code but for some reason it kept messing up the formatting. – Jonathan Kinlay Jan 14 '19 at 17:42
• I posted the code. (a very laborious process!). Anyway the suggested initialization of Vw didn't work in this case. – Jonathan Kinlay Jan 14 '19 at 18:02
• Try Module[{..., Vw = {{0.}},...}...]. – Michael E2 Jan 14 '19 at 18:13
• I suggest you give us the code you are using that works before attempting to Compile[] it. Having working code makes things a lot easier to understand. – Somos Jan 14 '19 at 21:08