How to add any number of variables together in all combinations?

I am trying to solve the three sum problem. It states that when provided a vector of a given length, three of the numbers in the vector add to zero. I am tasked with finding any and all of the combinations of numbers that add to zero.
For example, if the vector input is [3 1 3 -4 -6], the answers the code should output are: [3 1 -4], [3 1 -4] (repeated because two 3s are given) and [3 3 -6].
As of right now, I have code that assigns a variable to each of the numbers in the matrix:
---------------------------------
F = [3 1 3 -4 -6 ]; H = size(F); G = H(1,2);
for n = 1:G eval(['k' num2str(n) '= F(n)']) end
---------------------------------
What I need to do now is find out how to sum every combination of three of the numbers. If anyone could help me with this I'd be very grateful! Thank you for your time!

답변 (2개)

Cedric
Cedric 2013년 4월 25일
편집: Cedric 2013년 4월 25일

1 개 추천

You can use NCHOOSEK. You should avoid using EVAL actually, which is quite slow, and rarely appropriate. Also, look at the doc of SUM and see how you can specify the dimension along which it has to perform the summation; this should be useful to you.

댓글 수: 2

I appreciate your quick response. I should have mentioned in my original post that I want to avoid using the nchoosek function all together. I know this is inefficient and makes the process much longer and more difficult.
Cedric
Cedric 2013년 4월 25일
편집: Cedric 2013년 4월 25일
Can you use RANDPERM or PERMS?
If not, there would be a not-that-simple solution based on BSXFUN I guess, but if the statement of your HW disallows this kind of functions, you might end up implementing a triple FOR loop, or a double FOR and and a FIND.
If you end up implementing a solution based on loops, "think on paper" and once you have an algorithm implement it (don't start thinking "what command should I type).
The triple FOR loop, for example, would be based on an approach where you sum up elements 1, 2, 3 of F (whose values are 3, 1, 3) in a first step and check whether the sum is null, then you sum up elements 1,2,4 and perform the same test, then 1,2,5, etc.
On this note, I'm off for the night!

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

카테고리

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

질문:

2013년 4월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by