Store trios of values from different vectors in an only vector
3 views (last 30 days)
Show older comments
Hi guys!
I am trying to store trios of values (intengers values from 1 to 100) which fulfill an equation. The equation in this case is z^2=x^2+y^2.
I have tried it many ways, but none of them have worked correctly.
Now I am trying to use a couple of FOR loops in order to analyze every value of x and y, and finally determine which values of z I need. I am trying to solve this part with an IF inside the two FOR loops, but it is not working.
I do not know how can I store the diferent trios of values inside an only vector.
I was wondering if you could help me. Thanks!
12 Comments
Accepted Answer
John D'Errico
on 2 Oct 2022
Please stop posting the same question multiple times. You made some effort though.
First, learn to use meshgrid.
[X,Y] = meshgrid(1:100);
Next, compute Z, for EVERY values of X and Y.
Z = sqrt(X.^2 + Y.^2);
A sample values of Z is
Z(5,8)
or
Z(60,83)
You have found a solution only when z is an integer, AND Z is no larger than 100.
Can you now test to see which elements of Z are both an integer, AND no larger than 100? Even better, can you do that without using loops? Can you use find? It might make sense to keep only the solutions where X<=Y, as the problem is symmetric. If (x,y,z) is a solution, then so is (y,x,z). So you should discard the cases that yield these replicate solutions.
Could you have done this using loops? OF COURSE!
XYZsolutions = zeros(0,3);
for x = 1:100
for y = x:100
% Note this automatically discards the cases where x is greater than y.
% if you wanted to keep them, then have the y loop run form 1 to 100.
z = sqrt(x^2 + y^2)
% now you need to test to seee if z is an integer.
% You need to test to see if z is not greater than 100.
% You need to make some effort here, so why not think about how to perform those tests?
if ???????????????????????????
XYZsolutions(end+1,:) = [x,y,z];
end
end
end
4 Comments
Image Analyst
on 3 Oct 2022
OK, that extracts out only values where z is an integer. When I first read it, I saw that x and y were integers but I hadn't realized that z also had to be an integer also (but I do now). 😃
More Answers (1)
Image Analyst
on 2 Oct 2022
Edited: Image Analyst
on 2 Oct 2022
Try using meshgrid
x = 1 : 100;
y = 1 : 100;
% Get an x and a y for every location.
[X, Y] = meshgrid(x, y);
% Construct the surface
z = sqrt(X .^ 2 + Y .^ 2);
% Display the surface
surf(z, 'EdgeColor','none')
colorbar
xlabel('x')
ylabel('y')
zlabel('z')
% Find x,y,z triplets
triplets = [X(:), Y(:), z(:)]
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!