create a function of Pythagorean triples

조회 수: 9 (최근 30일)
MATLABnoob1
MATLABnoob1 2016년 3월 28일
답변: Anil Badiger 2019년 6월 5일
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

답변 (2개)

John D'Errico
John D'Errico 2016년 3월 28일
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 2019년 6월 5일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by