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

댓글 수: 2

Guillaume
Guillaume 2016년 5월 17일
Your example does not match the code provided since for arr1 = 2 and arr2 = 0, Result = 4 according to your formula.
So now we're left to guess as to what you really want.
alic mart
alic mart 2016년 5월 17일
Sorry I had copied the result from another formula. You're correct the result is 4. And I want to get every possible combination for example arr1 = 5 and arr2 =7 , arr1=0 and arr2 = 9 etc.

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

답변 (3개)

the cyclist
the cyclist 2016년 5월 17일
편집: the cyclist 2016년 5월 17일

0 개 추천

So, you want 120 X 120 combinations?
I think you probably want to use bsxfun to do the pairwise 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.
Guillaume
Guillaume 2016년 5월 17일
편집: Guillaume 2016년 5월 17일

0 개 추천

Assuming you're asking how to generate the cartesian product of the set [0:15] with itself:
[arr1, arr2] = ndgrid(0:15);
A = [arr1(:), arr2(:)];
Result = prod(A, 2) + sum(A.^2, 2);
array2table([A Result], 'VariableNames', {'arr1', 'arr2', 'Result'})

댓글 수: 2

alic mart
alic mart 2016년 5월 17일
is it possible to do that without changing the 'Result' formula? thanks
The 'Result' formula is not changed. It's just written in matlab. You can of course write it less efficiently as either:
Result = A(:, 1) .* A(:, 2) + A(:,1).^2 + A(:, 2).^2;
%or
Result = arr1(:) .* arr2(:) + arr1(:).^2 + arr2(:).^2;

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

John D'Errico
John D'Errico 2016년 5월 17일
편집: John D'Errico 2016년 5월 17일

0 개 추천

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.

카테고리

도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2016년 5월 17일

편집:

2016년 5월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by