How can this code run through all possible combinations of numbers in two separate arrays?

5 views (last 30 days)
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?

Accepted Answer

Image Analyst
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

More Answers (1)

Roger Stafford
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
Matthew
Matthew on 7 Dec 2014
This doesn't quite solve the problem. This outputs the last value of each array (as a and b), but doesn't provide me with a way to place every possible input combination into the equation. So instead of receiving answers like
y = [1+4 , 1+5, ... , 3+6]
I only receive
y = [3+6]
Roger Stafford
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. "

Sign in to comment.

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!