Vectors seen as a combination of other vector's elements
Show older comments
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
Answers (2)
madhan ravi
on 12 Apr 2019
[X,Y,Z]=meshgrid(a,b,c);
[X(:),Y(:),Z(:)]
3 Comments
Guillaume
on 12 Apr 2019
Personally, I'd use ndgrid instead of meshgrid. ndgrid works for higher dimensions, and operates consistently on all dimensions whereas meshgrid swaps the order of the first two dimensions.
Both will produce the same result, just wih a different ordering.
madhan ravi
on 12 Apr 2019
Yes, I agree.
Luca Freilino
on 12 Apr 2019
Guillaume
on 12 Apr 2019
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));
6 Comments
Luca Freilino
on 12 Apr 2019
Guillaume
on 12 Apr 2019
What would the output be if you had matrices as inputs, e.g.
in = {[1 2;3 4], [5 6 7;8 9 10; 11 12 13]}
combs = ???
Luca Freilino
on 12 Apr 2019
Torsten
on 12 Apr 2019
Why not simply reshaping matrices to vectors:
A = A(:)
before applying Guillaume's code ?
madhan ravi
on 12 Apr 2019
Same thought as Torsten's but your question is most likely solved by Guillaume's method.
Luca Freilino
on 12 Apr 2019
Edited: Luca Freilino
on 12 Apr 2019
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!