Ragged array of variables

The number of variables in the problem I am trying to solve is \sum_{i=0}^N x_i where x_i is the number of actions that the i^{th} agent takes, i.e. one real variable per action.

The best way to model such variables would be to have a ragged array of variables, but I could not find any way of creating a cell of variables. Is it possible and is there an example which could guide me?


Creating a N \times (\max_i x_i) matrix of variables and explicitly setting the extra variables to zero will be prohibitively expensive since the number of actions follows a power-law, i.e. few x_i are very large (\approx 10^3), while most are very small (\approx 10).

The solution I have in mind is to create a single variable of length \sum_{i=0}^N x_i and then to index into it manually.

I’m afraid I don’t have a particularly good solution for you. I think your option of indexing in the variable manually is your best bet. Here’s how I’d do it. Given a vector of length lens,

nx = length(lens);
variable xx(sum(lens)))
xc = cell(1,nx);
ndx = 0;
for k = 1 : length(lens)
    xc{k} = x(ndx+1:ndx+lens(k));
    ndx = ndx + lens(k);
end

It’s neither pretty nor fast but it will work.

1 Like