Creating a script that finds all triple of the Pythagorean theorem.

조회 수: 32 (최근 30일)
Alec Baird
Alec Baird 2016년 3월 17일
편집: Stephen23 2018년 1월 3일
I'm new to Matlab, and completely stuck on this one. I'm supposed to generate a script that finds all combinations of the Pythagorean triples with integers <= 50. I got most of the way there, but I can't figure out out to get rid of the repeating numbers. Here's what I have.
n=1;
for a_ = 1:50
for b_ = 1:50
c_=sqrt(a_^2+b_^2);
if c_==round(c_)
if c_<=50
a(n)=a_;
b(n)=b_;
c(n)=c_;
n=n+1;
end
end
clear c_
end
end
Pyth=[a',b',c'];
disp(Pyth)
  댓글 수: 2
Richard Lu
Richard Lu 2017년 11월 28일
편집: Richard Lu 2017년 11월 28일
try it out:p
Stephen23
Stephen23 2018년 1월 3일
편집: Stephen23 2018년 1월 3일
See Jos's answer for a solution that actually answers the question (i.e. only returns Pythagorean integer triplets).

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

채택된 답변

John BG
John BG 2016년 3월 17일
편집: Jan 2017년 12월 27일
Alec
use the very useful function combinator, available from MATLAB CENTRAL, i copy it here at the end of my answer.
Pytha_triple=uint64(combinator(50,3,'p','r'))
=
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
...
50 50 45
50 50 46
50 50 47
50 50 48
50 50 49
50 50 50
If you find this answer of any help solving your question, please click on the thumbs-up vote link,
thanks in advance
John
  댓글 수: 2
Jos (10584)
Jos (10584) 2017년 11월 28일
This merely shows the combinations of three integers from 1 to 50, not only Pythagorean integer triplets,like [3 4 5].
John D'Errico
John D'Errico 2017년 12월 27일
A bit of a travesty to have an accepted answer on a question where nothing useful was provided.

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2017년 11월 28일
ab = nchoosek(1:50,2) ; % all unique combinations of values
c = sqrt(sum(ab.^2,2)) ; % hypothenuse
tf = c == fix(c) & c <= 50 ; % check for integer and limits
PythgoreanIntegerTriplets = [ab(tf,:) c(tf)]

카테고리

Help CenterFile Exchange에서 Geometry and Mesh에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by