Create a multidimensional Grid

Hi,
i try to create a multidimensional grid with these scalar values but i cannot wrap my head around how the code would look like if i use more than 2 or 3 Factors (I obviously don't want to make for each possible number of Factors an extra
if isequal(length(Factors),2), if isequal(length(Factors),3),if isequal(length(Factors),4),if isequal(length(Factors),5)
)
clear all;
clc;
FactorGrid = [];
%Three differend Factors, each Factor has 4 different possible values(each Factor has to have the same amount of different possible values )
Factors{1}= [1,2,3,4];
Factors{2}= [55,66,77,88];
Factors{3}= [101,202,303,404];
%For using 2 Factors
if isequal(length(Factors),2)
for k = 1:length(Factors{1})
for l = 1:length(Factors{2})
FactorGrid{end+1,1} = [Factors{1}(k),Factors{2}(l)];
end
end
end
%For using 3 Factors
if isequal(length(Factors),3)
for k = 1:length(Factors{1})
for l = 1:length(Factors{2})
for m = 1:length(Factors{3})
FactorGrid{end+1,1} = [Factors{1}(k),Factors{2}(l),Factors{3}(m)];
end
end
end
end
I tried to work with
perms()
but that didn't work either.
The grid should have the size of possible values^number of Factors, so in this case 4^3.
Can you help me out?

 採用された回答

Fab
Fab 2021 年 5 月 30 日

0 投票

Ok thanks, this does the job for me:
A= [1, 2, 3, 4]';
B= [55, 66, 77, 88]';
C= [101, 202, 303, 404]';
ma=size(A,1);
mb=size(B,1);
mc=size(C,1);
[a,b,c]=ndgrid(1:ma,1:mb,1:mc);
product = [A(a,:),B(b,:),C(c,:)];

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2021 年 5 月 30 日

0 投票

[FG{:}] = ndgrid(Factors{:});

2 件のコメント

Fab
Fab 2021 年 5 月 30 日
cellsForNgrid = cell(1,numel(Factors));
[cellsForNgrid{:}]=ndgrid(Factors{:});
cellsForNgrid was needed since "[FG{:}]" doesn't contain the amount of cells that are needed.
Walter Roberson
Walter Roberson 2021 年 5 月 30 日
True. Or you can
[cellsForNgrid{1:numel(Factors)}] = ndgrid(Factors{:});

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

Fab
Fab 2021 年 5 月 30 日

0 投票

How would this ndgrid work with my code?
Read the documentation but i don't get the results i want.
I attached a picture of the result, if i use your code.

カテゴリ

ヘルプ センター および File ExchangeDiscrete Math についてさらに検索

質問済み:

Fab
2021 年 5 月 30 日

編集済み:

2021 年 5 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by