How to do a cycle through a N-dimensional grid, if n is not fixed?

2 ビュー (過去 30 日間)
Mr M.
Mr M. 2017 年 12 月 11 日
編集済み: Stephen23 2022 年 2 月 9 日
I know there is ngrid, but you have to know n. What if I want to do n for cycles, but I don't know n at the moment, it is a variable.
  2 件のコメント
Mr M.
Mr M. 2017 年 12 月 11 日
And one additional thing. Since number of gridpoints can be very large. It would be nice to have a solution where you don't want to store the gridponts, just go through them!
Stephen23
Stephen23 2017 年 12 月 11 日
Mr M.'s "Answer" moved here:
I would like to go through the grid points of an N-dimensional grid, but N is an input parameter. For example in each dimension I would like K gridponts, so I have KxKxKx...xK = K^N points. If i know that N=2, I can use meshgrid, or in case of N=5, I can use [X1,X2,X3,X4,X5] = ngrid(1:K,1:K,1:K,1:K,1:K); But N is a variable! How to go through the gridpoints?

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2017 年 12 月 11 日
編集済み: Guillaume 2017 年 12 月 11 日
Please don't use answer boxes when commenting. Use the Comment on this Question or comment on this Answer box.
If I understood you want to generate N Nd arrays with ndgrid with N being unknown in advance. No problem, use the expansion of cell arrays into comma-separated lists to do that:
N = 5; %value can change
K = 4; %value can change
Ndarrays = cell(1, N); %create cell array to receive outputs of ndgrid
[Ndarrays{:}] = ndgrid(1:K); %fills all N Nd arrays
And in case, your K is different for each dimension, then:
N = randi([3 6]); %randomly chose N between 3 and 6. For demo
K = randi([2 7], 1, N); %randomly chose N K between 2 and 7. For demo
sizeinputs = arrayfun(@(k) 1:k, K, 'UniformOutput', false); %generate the inputs of ndgrid as a cell array
ndarrays = cell(1, N);
[ndarrays{:}] = ndgrid(sizeinputs{:});
  9 件のコメント
Stephen23
Stephen23 2022 年 2 月 9 日
編集済み: Stephen23 2022 年 2 月 9 日

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Preprocessing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by