How to create a array/vector/matrix with number of dimensions unknown at declaration time.

101 views
Skip to first unread message

Jeff Alstott

unread,
Dec 2, 2016, 12:58:58 AM12/2/16
to Stan users mailing list

I'm having issues in a transformed data block with arrays and vectors whose size can only be determined after inspecting some of the data.

This code won't work, because two of the variables aren't defined at the beginning of the block:

int N_gap_updates;
N_gap_updates = sum(gap_lengths);
int gap_techs[N_gap_updates];
int gap_ts[N_gap_updates];

This code won't work, because the array variables will think N_gap_updates == 0:

int N_gap_updates;
N_gap_updates = sum(gap_lengths);
int gap_techs[N_gap_updates];
int gap_ts[N_gap_updates];

What to do?

Daniel Lee

unread,
Dec 2, 2016, 1:27:16 AM12/2/16
to stan-...@googlegroups.com
We'll have compound define and declare soon, which wi solve the problem. For now, a little code duplication will work. 

int N_gap_updates;
int gap_techs[sum(gap_lengths)];
int gap_ts[sum(gap_lengths)];
N_gap_updates = sum(gap_lengths);

If you think that's gonna be massively wasteful, it isn't going to be a problem in practice. 


Daniel


--
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.

Jeff Alstott

unread,
Dec 2, 2016, 1:35:50 AM12/2/16
to Stan users mailing list
That's what I thought the solution would be. The problem is that the minimal example I gave is actually not my main problem. I have a situation where merely calculating what the size of a vector should be is a dozen or more lines of code. Is the same solution still suggested?

Daniel Lee

unread,
Dec 2, 2016, 7:35:16 AM12/2/16
to stan-...@googlegroups.com
Yes, but you shouldn't ever need to repeat dozens of lines of code. You can write a function for that. Or pass that as data from the outside. 


Daniel
Reply all
Reply to author
Forward
0 new messages