Too bad, I had it right the first time then tried to
"simplify". You need to put that matrix declaration in
a local lower down, as in:
/**
* Return what R computes as x[is == target, ]
*/
matrix foo(matrix x, int[] is, int target) {
if (size(is) != rows(x))
reject("illegal input"); // stricter than R's broadcasting
// count number of rows in result
int count;
count <- 0;
for (n in 1:size(is))
if (is[n] == target)
count <- count + 1;
// assign rows in result
{
matrix[count, cols(x)] result;
int pos;
pos <- 1;
for (n in 1:size(is)) {
if (is[n] == target) {
result[pos] <- x[n]; // assigns entire row
pos <- pos + 1;
}
}
return result;
}
}
I still haven't tried it, but it should work. I love
these little programming puzzles --- it's like a job interview
for being a programmer these days :-)
- Bob
> On Mar 4, 2016, at 7:34 PM, Jonah Gabry <
jga...@gmail.com> wrote:
>
> That's a cool function! Minor thing: I think it will give an error because count is used in matrix[count, cols(x)] result; before it's declared.
>
>
> --
> You received this message because you are subscribed to the Google Groups "Stan users mailing list" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
stan-users+...@googlegroups.com.
> To post to this group, send email to
stan-...@googlegroups.com.
> For more options, visit
https://groups.google.com/d/optout.