Gregory
Gregory

Reputation: 349

General nested for-loop for N x d matrix in Julia

I would like to write a function in Julia that takes in a N x d numeric matrix where N is number of data points and d is the number of parameters:

  1. Extract the min and max along each dimension (this I can do)
  2. User-specified level of discretization (e.g. 1.0 in the below example)
  3. Returns a matrix M x d which contains all combinations (see description of M below).

As a simple example with d = 5, I have taken the results of part 1 where I obtain the min and max along each dimension.

minX = [ -1.0  -0.5  -1.1  -1.0  -0.9]
maxX = [3.8  2.5  1.8  3.1  2.3]
test=[minX[i]:1.0:maxX[i] for i in 1:5]

(I have purposely taken a coarse step of size 1.0). My question is how can I loop through test in a systematic way (without making 5 for loops) such that I get all combinations that result from the discretization which would yield a matrix of size M x d where

M = prod([length(x) for x in test]) # 1200 in this example.

Upvotes: 1

Views: 69

Answers (1)

张实唯
张实唯

Reputation: 2862

There is a "hidden" function Iterators.product that iterates the cartesian product set.

R = Iterators.product(test...)
size(R) # (5, 4, 3, 5, 4)

All you need is then concatenating the elements in R vertically. It can be a single loop over R to fill a pre-allocated array, or more concisely

[map(transpose ∘ collect, R)...;] # 1200 * 5 matrix

Upvotes: 3

Related Questions