Check what values of three variables fulfill a certain condition

4 次查看(过去 30 天)
Hi guys! I'm stuck with a problem where if have to find all the values of x, y and z which fulfill the next equation: x^2+y^2=z^2.
I have tried it in many ways, but I can't get a result.
I don't know if you could help me..
Thank you very much!
x=[1:1:100]; % values of X
y=[1:1:100]; % values of Y
z=[1:1:100]; % values of Z
found=0;
for i=1: length(x)
for k=1:length(y)
for l=1: length(z)
if x.*x+y.*y==z.*z
found=1;
end
end
end
end
if found==1
disp(x,y,z)
end

回答(1 个)

Walter Roberson
Walter Roberson 2022-10-1
You do not need to loop over z. Instead, take z = sqrt(x.^2+y.^2) and test to see whether z is an integer.
And... vectorize. For a given x value you can compute for a vector of y values, and use logical indexing to figure out which (if any) entries match.
I have implemented a fully vectorized version that uses no loops at all, and I have implemented a version that uses a single loop; both approaches work fine. I am not posting the code here because you are obviously working on an assignment.
  1 个评论
ABG
ABG 2022-10-1
Thanks for the answer Walter. Actually is not an assignment (is a preparatory course, I want to get into programming with matlab for my master's degree) and this part of the course is really important for me in order to understand it all.
Is it possible from you to post one of your versions please? As it will be easier for me to understand how to complete operate.
Thank you so much for your help!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by