How do I get every combination of 3 vectors?
1 次查看(过去 30 天)
显示 更早的评论
Hello!
I have 3 vectors, one is a 35x1, one is a 31x1 and the last one is a 13x1. I want to create some kind of loop that outputs a number from the first, a number from the second, and a number from a third, over and over, eventually outputting every combination.
If I am not clear, please comment.
Thanks!
-Kevin
0 个评论
采纳的回答
Bruno Luong
2020-8-2
编辑:Bruno Luong
2020-8-2
yourvector1 = ...
yourvector2 = ...
yourvector3 = ...
Then
c = {yourvector1, yourvector2, yourvector3};
c = flip(c);
[c{:}] = ndgrid(c{:});
c = cellfun(@(x) x(:), flip(c), 'unif', 0);
c = cat(2, c{:});
check
disp(c)
3 个评论
Bruno Luong
2020-8-2
编辑:Bruno Luong
2020-8-2
c is an array of combination.
- Row dimension corresponds to different combination,
- Column dimension corresponds to yourvector1, yourvector2, yourvector3 values.
You have to tell us what you meant by "use one at the time", but it probably goes like this
for i=1:size(c,1)
combi = c(i,:); % 1 x 3 vector
% do something with it
...
end
You probably need more learning of basic stuff of MATLAB/programming.
更多回答(2 个)
Image Analyst
2020-8-2
Here's a for loop way to do it:
% Create 3 sample vectors, one is a 35x1, one is a 31x1 and the last one is a 13x1.
v1 = (1:35)'; % Actual values are whatever yours are - not a ramp like this.
v2 = (1:31)';
v3 = (1:13)';
% Get 3 random selection orderings:
order1 = randperm(length(v1));
order2 = randperm(length(v2));
order3 = randperm(length(v3));
% Now make 3 loops
for k1 = 1 : length(order1)
index1 = order1(k1);
for k2 = 1 : length(order2)
index2 = order2(k2);
for k3 = 1 : length(order3)
index3 = order3(k3);
fprintf('Processing index %d from v1, index %d from v2, and index %d from v3.\n', index1, index2, index3);
end
end
end
Of course you can do it with a built-in function rather than loops like Matt showed you.
6 个评论
Image Analyst
2020-8-2
You're welcome. Thanks for voting for it though. Matt's answer is the more MATLAB-y, vectorized way of doing it and is probably what I would have done. I just offered the looping way of doing it because that's what you specifically asked for, and sometimes the vectorized methods use functions, which, honestly, can be more confusing to beginners than a simple, intuitive for loop.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!