Vectors seen as a combination of other vector's elements

1 回表示 (過去 30 日間)
Luca Freilino
Luca Freilino 2019 年 4 月 12 日
編集済み: Luca Freilino 2019 年 4 月 12 日
Hi everyone.
I have a problem that I think to be quite easy, but I can't succeed in solving it.
I have four vectors of different length (a, b, c, d). I'd like to have a final vector (V) which contains all the combinations of their elements.
eg, if I had a = [1 2 3], b = [4 5], c = [6], V should be [1 4 6; 1 5 6; 2 4 6; 2 5 6; 3 4 6; 3 5 6].
Now I'm using four nested for cycle, but I'd like to find a faster solution, without using the cycle but maybe some logical solutions.
Thank you in advance. Luca
P.S. I leave the portion of my code:
for n = 1:length(comb_n)
for i = 1:length(comb_i)
for c = 1:length(comb_c)
for a = 1:length(comb_a)
combinations(index,1:number_surrogates) = [comb_n(n,:), comb_i(i,:), comb_c(c,:), comb_a(a,:)];
index = index+1;
end
end
end
end

回答 (2 件)

madhan ravi
madhan ravi 2019 年 4 月 12 日
[X,Y,Z]=meshgrid(a,b,c);
[X(:),Y(:),Z(:)]
  3 件のコメント
madhan ravi
madhan ravi 2019 年 4 月 12 日
Yes, I agree.
Luca Freilino
Luca Freilino 2019 年 4 月 12 日
I tried with meshgrid, but it doesn't work since I've always four vectors. I forgot to say that these vectors could be even matrices (eg the second one could be a (N,2) size). Could you explain me how to use the ndgrid? I know the function, but I have no idea which conditions should I use. Thanks, Luca

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


Guillaume
Guillaume 2019 年 4 月 12 日
This is the generic version of Madhan's answer. Works for any (reasonable!) number of inputs.
in = {[1, 2, 3], [4, 5], 6}; %cell array of vectors.
combs = cell(size(in));
[combs{:}] = ndgrid(in{:});
combs = reshape(cat(numel(combs) + 1, combs{:}), [], numel(combs));
You could also download AllComb from the filexchange, which does the same.
  6 件のコメント
madhan ravi
madhan ravi 2019 年 4 月 12 日
Same thought as Torsten's but your question is most likely solved by Guillaume's method.
Luca Freilino
Luca Freilino 2019 年 4 月 12 日
編集済み: Luca Freilino 2019 年 4 月 12 日
It's not a good solution or, at least, this is not good for my problem. I forward the code, it shoud be easier to explain:
v = [1 2 2 1];
a = 1:12;
b = 13:29;
c = 30:39;
d = 40:47;
A = nchoosek(a,v(1));
B = nchoosek(b,v(2));
C = nchoosek(c,v(3));
D = nchoosek(d,v(4));
What I need is the family of combination, like:
1 13 14 30 31 40;
1 13 14 30 31 41;
.........................
1 13 14 30 32 40;
.........................
.........................
.........................
12 28 29 38 39 47

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by