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

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?

 채택된 답변

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

Image Analyst, you deserve a cookie.
Regarding your comment to Roger, to get the sums of all combinations:
theSums = AA + BB;
theSums is a vector of all possible sums.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

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

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]
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. "

댓글을 달려면 로그인하십시오.

카테고리

질문:

2014년 12월 7일

댓글:

2014년 12월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by