Provided a 1D array of integers, find all combinations of 3 values from this set such that: a+b+c=0
Show older comments
Ok, I can't figure out where I what I am doing wrong in my code. I have tried debugging but without knowing what they are asking me to fix it's kind of hard to just go from that. Any advice on how to correct this would be greatly appreciated.
function [S] = ThreeSum(i, j, k)
for i=0;
i < S;
for j = i + 1;
j < S;
for k = j + 1;
k < S;
if a(i) + a(j) + a(k) == 0;
end
end
end
end
end
Accepted Answer
More Answers (2)
John D'Errico
on 22 Feb 2012
What exactly is the purpose of statements like this:
i < s;
What do you think they do?
Next, what do you think MATLAB does when it sees a loop like this:
for i = 0;
end
How many times does it execute that loop?
I think you need to look at the help for for. Read the documentation. Look at the examples. Don't just write code as you might imagine it will work, perhaps what might work in some other language, because your imagination will probably be wrong.
And, oh, by the way, matlab indexing starts at 1, NOT at 0. You cannot try to find the vector element a(0) and not expect to get an error.
Finally, some think that it is poor programming practice to use i and j as loop variables, as i and j are already defined in MATLAB as the imaginary unit for complex numbers, sqrt(-1). Personally, I like to use i and j for that purpose myself, and I tend not to work in the complex domain, so it it not an issue for me.
Walter Roberson
on 22 Feb 2012
Your code uses "S" and "a" without defining them.
Your line
i < S;
will compare i to the non-existent S, causing an error. But if S had been defined, whatever the result of the comparison was, it would just throw away the result because of the semi-colon at the end of the line.
Your line
for i=0;
runs a loop with "i" set only to the value 0, and no other value.
I would suggest you need to review the syntax for MATLAB "for" loops: it is not the same as the syntax for C.
1 Comment
Jan
on 22 Feb 2012
Let me mention, that "for i=0; i<S; <LoopBody>" is even not valid C.
Categories
Find more on Matrix Indexing 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!