Problem 61010. q-dimensional Cartesian product

Your mission, should you choose to accept it, is to compute a q-dimensional Cartesian product, as follows. Let the input G be an 1×q cell array of vectors of size 1×n_i each (here and in the following, 1≤i≤q). The output V should be a q-dimensional cell array of size n_1×n_2×…×n_q such that for 1≤k_i≤n_i, V{k_1,k_2,…,k_q} is equal to the vector [ G{1}(k_1), G{2}(k_2), …, G{q}(k_q) ]. In other words, the indices into V are the Cartesian product of the indices into the vectors in G, and each element of V is the combination of values from those vectors at those indices.
An example: if G = { 1:2, 3:4 }, then V = { [1 3], [1 4] ; [2 3], [2 4] }; if G = { 1:2, 3:4, 5:6 }, then V(:, :, 1) = { [1 3 5], [1 4 5] ; [2 3 5], [2 4 5] } and V(:, :, 2) = { [1 3 6], [1 4 6] ; [2 3 6], [2 4 6] }; and so on.
Note: due to the way MATLAB handles trailing singleton dimensions, ndims(V) will report a number less than q if n_j = … = n_q = 1 for some j≤q. This is alright since indexing V along q dimensions will still work.
Note 2: cheating isn't banned by the test suite, but don't do it. It's not sportsmanlike.

Solution Stats

100.0% Correct | 0.0% Incorrect
Last Solution submitted on Oct 02, 2025

Solution Comments

Show comments

Problem Recent Solvers1

Suggested Problems

More from this Author19

Problem Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!