create a function of Pythagorean triples

8 visualizaciones (últimos 30 días)
MATLABnoob1
MATLABnoob1 el 28 de Mzo. de 2016
Respondida: Anil Badiger el 5 de Jun. de 2019
hi. i'm trying to create a function of Pythagorean triples, i need to be able to input the sum of the sides (a,b,c) into my function and retrieve an output of all the different combinations of sides that add to that sum. i'm only just of recently learning how to use MatLab and this is driving me insane, so i came here hoping someone could point me in the right direction. any answers will help, thanks! this is what i have so far (i have no idea):
% code
function [ T ] = PTriple( x )
for a = 1:x
for b = 1:x
for c = 1:x
if c == sqrt(a^2 + b^2)
fprintf ('(%d,%d,%d)\n',a,b,c');
end
end
end
end
end
% code

Respuestas (2)

John D'Errico
John D'Errico el 28 de Mzo. de 2016
I know that I've seen this question before. In fact, I answered it then , and attached pythagsum.m to my answer. I had to tweak it as I recall to make sure it generated all possible solutions, but it will work as posted.
If your intent is to use a nested loop, then your loops can be made more efficient.
1. Since all triples have side lengths at least 3, start with 3, not 1.
2. No triples ever have two sides that are the same length.
3. For uniqueness, we can require that a<b<c
4. If X is the sum of the side lengths, then the smallest side length could never be larger than X/3.
5. Since you KNOW the sum, there is NO need to use a triple loop at all. A double loop will suffice.
therefore the limits for your loops might be more intelligently chosen as:
for a = 3:(X/3)
for b = (a+1):((X - a)/2)
c = X - a - b;
if (a^2 + b^2) == c^2
something like that might work.

Anil Badiger
Anil Badiger el 5 de Jun. de 2019
function flag = isRightAngled1(a,b,c)
flag = false;
m = max(max(a,b),c)
m = m*m; a = a*a; b= b*b; c = c*c;
if m == a+b
flag = true;
elseif m == b+c;
flag = true;
elseif m == c+a;
flag = true;
end
end
Use this, it might help you.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by