triangle edges , triplet
古いコメントを表示
Firstly, I am a beginner, sorry for wrongs
function rightTriangleEdges(listOfIntegers) that returns a
triplet [x y z] from the list of integers listOfIntegers where x, y and z satisfy
x^2 + y^2 = z^2
Unless triplet exist the function return an empty array.
for example input output
rightTriangleEdges ([1 2 3 4 5 6 7 8]) [3 4 5]
rightTriangleEdges (1:4) []
I did like this but i guess i am in wrong way:
function myList = rightTriangleEdges(listOfIntegers)
clear all; close all; clc;
for listOfIntegers=[];
A=1:length(listOfIntegers);
end
for i=1:length(A(1,:))
for j=1:length(A(1,:))
for k=1:length(A(1,:))
for r=length(listOfIntegers)
r(i)=((A(1,i))^2)+((A(1,j))^2)==(A(1,k))^2
end
end
end
end
disp(num2str(r(i)))
end
listOfIntegers=[1 2 3 4 5 6 7 8];
rightTriangleEdges(listOfIntegers)
回答 (1 件)
Steven Lord
2020 年 12 月 7 日
function myList = rightTriangleEdges(listOfIntegers)
clear all; close all; clc;
These three commands should IMO almost never appear in a function file. In this context close all and clc are annoying but perhaps not too bad. But clear all destroys the input with which the user called your function!
for listOfIntegers=[];
A=1:length(listOfIntegers);
end
A will not be defined after this code. The body of the for loop will execute 0 times. Therefore:
for i=1:length(A(1,:))
this line will error.
for j=1:length(A(1,:))
for k=1:length(A(1,:))
for r=length(listOfIntegers)
r(i)=((A(1,i))^2)+((A(1,j))^2)==(A(1,k))^2
Do not attempt to change the value of a loop variable inside the loop. While that does technically work, at the start of the next iteration MATLAB will overwrite the loop variable's value with the next iterate.
Let's take a step back. I'm going to give you a list of numbers. Walk me through the steps that you would follow to answer the question (identifying all Pythagorean triples in the list) if all you had to work with was a pencil and paper (or marker and whiteboard, or stick and sandbox, etc.) Once you know the steps that you can use to solve the problem that may make implementing the solution easier.
The list of numbers is [1 2 3 4 5 6]
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!