フィルターのクリア

Pythagorean triples - wrong output in loop

1 回表示 (過去 30 日間)
sznailc
sznailc 2021 年 11 月 3 日
回答済み: the cyclist 2021 年 11 月 3 日
Hello, I have this piece of code, it computes pythagorean triples, then adds them in a matrix, but in output for some reason it adds lines with zeros. How do I change the code to run properly?
And 1 more thing how to make it print sorted by a+b+c column, not by a like now?
UPD. I have solved 1 part of the question with "R = reshape(nonzeros(R), I, 4);
"
function [R, I] = pyth_tri(N)
I = 0;
for a = 3:N/3
for b = a:N/3
for c = b:N
if (a^2 + b^2) == c^2 && a ~= 0 && b ~= 0 && c ~= 0
R(a, :) = [a+b+c, a, b, c]
I = I + 1;
end
end
end
end
end

採用された回答

the cyclist
the cyclist 2021 年 11 月 3 日
You need
R(I+1, :) = [a+b+c, a, b, c];
rather than
R(a, :) = [a+b+c, a, b, c];
For sorting, after your run your algorithm, run
R = sortrows(R,1)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by