for a=1:50; %numbers 1 through 50
for b=1:50;
c=sqrt(a^2+b^2);
if c<=50&c(rem(c,1)==0);%if display only if c<=50 and c=c/1 has remainder of 0
pyth=[a,b,c];%pythagorean matrix
disp(pyth)
else c(rem(c,1)~=0);%if remainder doesn't equal to 0, omit output
end
end
end
answer=
3 4 5
4 3 5
5 12 13
6 8 10
7 24 25
8 6 10
8 15 17
9 12 15
9 40 41
10 24 26
12 5 13
12 9 15
12 16 20
12 35 37
14 48 50
15 8 17
15 20 25
15 36 39
16 12 20
16 30 34
18 24 30
20 15 25
20 21 29
21 20 29
21 28 35
24 7 25
24 10 26
24 18 30
24 32 40
27 36 45
28 21 35
30 16 34
30 40 50
32 24 40
35 12 37
36 15 39
36 27 45
40 9 41
40 30 50
48 14 50
This problem involves the Pythagorean theorem but we cannot use the built in function so I had to write one myself. The problem is for example columns 1 & 2 from the first two rows have the same numbers. How do I code it so it only deletes one of the rows if the columns 1 and 2 have the same number combination? I've tried unique function but it doesn't really delete the combinations. I have read about deleting duplicates from previous posts but those have confused me even more. Any help on how to go about this problem will help me immensely!
Thank you
welcome to StackOverflow.
The problem in your code seems to be, that
pyth
only contains 3 values,[a, b, c]
. Theunique()
funcion used in the next line has no effect in that case, because only one row is contained inpyth
. another issue is, that the valuesidx
andout
are calculated in each loop cycle. This should be placed after the loops. An example code could look like this:a few other tips for writing MATLAB code:
for
orif
/else
stements with a semicolonelse
statements cover any other case not included before, so they do not need a condition.Some performance reommendations:
a
andb
(a^2 + b^2 = b^2 + a^2) the b loop could be constrained tofor b=1:a
, which would roughly save you half of the loop cycles.&&
for contencation of scalar values, the second part is not evaluated, if the first part already fails (source).Regards,
Chris