How can this code run through all possible combinations of numbers in two separate arrays?
5 views (last 30 days)
Show older comments
Here is the problem I am having (on a small scale): what I need to do is take combinations of values from two separate matrices and treat them as inputs in an equation. I would like to input all possible combinations of the two parameters. For example:
A = [1 2 3]
B = [4 5 6]
y = (1 element of A) + (1 element of B)
Possible combinations to be used as inputs in an equation:
1 and 4
1 and 5
1 and 6
2 and 4
2 and 5
etc.
What is the best way to go about coding this?
0 Comments
Accepted Answer
Image Analyst
on 7 Dec 2014
You can use meshgrid:
A = [1 2 3]
B = [4 5 6]
[AA, BB] = meshgrid(A, B)
% Convert to column vectors
AA = AA(:);
BB = BB(:);
for k = 1 : length(AA)
fprintf('A = %d, B = %d\n', AA(k), BB(k));
end
2 Comments
Image Analyst
on 7 Dec 2014
Regarding your comment to Roger, to get the sums of all combinations:
theSums = AA + BB;
theSums is a vector of all possible sums.
More Answers (1)
Roger Stafford
on 7 Dec 2014
Use for-loops:
for iA = 1:length(A)
a = A(iA);
for iB = 1:length(B)
b = B(ib);
% Use a and b as inputs
end
end
2 Comments
Roger Stafford
on 7 Dec 2014
I disagree, Matthew. Each possible combination of a pairing from A and B are used as inputs a and b in those for-loops. In your example, there would be nine different combinations that would occur as inputs.
Is there something about your using pairs as inputs that you are not telling us? Perhaps you should explain at greater lengths what you mean by " Possible combinations to be used as inputs in an equation. "
See Also
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!