Array combination using pairs
Ältere Kommentare anzeigen
Hello I'm having trouble with a seemingly simple problem.
A = nchoosek(0:15, 2)
arr1 = A(:,1);
arr2 = A(:,2);
Result = arr1.*arr2 + arr1.^2 + arr2.^2;
I want to use all the combinations of arr1 and arr2 arrays to solve the Result equation and print out the following table:
arr1 arr2 Result
0 0 0
1 1 3
2 0 4
and so on.. but not all the combinations are used when I try this approach. What should I do to get all the possible combinations?
Thanks
Antworten (3)
the cyclist
am 17 Mai 2016
Bearbeitet: the cyclist
am 17 Mai 2016
So, you want 120 X 120 combinations?
It sounds like you might want
Result = bsxfun(@times,arr1,arr2') + bsxfun(@times,arr1,arr1') + bsxfun(@times,arr2,arr2');
but you'll want to double-check that.
[arr1, arr2] = ndgrid(0:15);
A = [arr1(:), arr2(:)];
Result = prod(A, 2) + sum(A.^2, 2);
array2table([A Result], 'VariableNames', {'arr1', 'arr2', 'Result'})
John D'Errico
am 17 Mai 2016
Bearbeitet: John D'Errico
am 17 Mai 2016
Two vectors are trivial.
help meshgrid
help ndgrid
[arr1,arr2] = meshgrid(0:15);
Result = arr1.*arr2 + arr1.^2 + arr2.^2;
If you want it as a vector,
Result = Result(:);
Actually, you might be slightly more efficient for this problem if you do it as:
Result = (arr1 + arr2).^2 - arr1.*arr2;
More dimensions are as easy, but beware of the curse of dimensionality.
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!