# Function with two-dimensional array as output

I am trying to figure out why my function isn’t working since I changed it from a 1-dimensional to 2-dimensional array output.

A very simple version of my function is below. Are there any obvious syntax errors?

``````functions {
vector[] out_func(int A, int B, real num1, real num2, vector vec1, vector vec2) {
vector[A] out[B, B];
out = { { vec1, num1*vec1 }, { num2*vec2, vec2 } }
return out;
}
}

data {
int A;
int B;
vector[A] vec1;
vector[A] vec2;
}

parameters {
real num1;
real num2;
}

transformed parameters {
vector[A] out[B, B] = out_func(A, B, num1, num2, vec1, vec2) ;
vector[A] lam[B];
for (b in 1:B)
lam[b] = { out[b, 1] + out[b, 2] }
}

``````

I get the “syntax error” output when I run it with the ^ under the r of return.

Thank you :)

I did also try

``````vector[,] out_func()
``````

but still got the same syntax error.

Not sure about this, but vector is 1dim object and you return `array`. So try with that?

1 Like

There are a couple of things that are causing errors here.

First, the return type needs to be a two-dimensional array of vectors:

``````vector[] out_func(int A, int B, real num1, real num2, vector vec1, vector vec2)
``````

Next, you’re missing semicolons at the end of two lines:

``````out = { { vec1, num1*vec1 }, { num2*vec2, vec2 } }
...
lam[b] = { out[b, 1] + out[b, 2] }
``````

And finally, you don’t need the array initialiser (`{}`) around the assignment to `lam`, since the `b`-th entry is a vector:

``````    vector[A] lam[B];
for (b in 1:B)
lam[b] =  out[b, 1] + out[b, 2]
``````

Fixing all of those, your model looks like:

``````functions {
vector[,] out_func(int A, int B, real num1, real num2, vector vec1, vector vec2) {
vector[A] out[B, B];
out = { { vec1, num1*vec1 }, { num2*vec2, vec2 } };
return out;
}
}

data {
int A;
int B;
vector[A] vec1;
vector[A] vec2;
}

parameters {
real num1;
real num2;
}

transformed parameters {
vector[A] out[B, B] = out_func(A, B, num1, num2, vec1, vec2) ;
vector[A] lam[B];
for (b in 1:B)
lam[b] = out[b, 1] + out[b, 2];
}
``````

Which compiles for me locally

2 Likes

Thank you. Was 100% the missing ; before the return.

Much appreciated.

2 Likes