MATLAB: Pythagorean triples up to Z without loops

pythagorean

I've been struggling with this problem for a while now and am looking for some insight.
The problem is in the form of a function: [A] = pyth(Z).
The problem is to find pythagorean triples where an output [A] is a [? x 3] matrix like:
a b c
3 4 5
6 8 10
5 12 13
where the highest value of c is a number Z.
The tricky part is not using loops.
I've been thinking of using meshgrid and reshape but can't quite put together how to use them. If anyone thinks of anything let me know! I'll be continuing to work on it in the meantime.

Best Answer

Instead of ‘meshgrid’ I would suggest using ‘ndgrid’:
[a,b,c] = ndgrid(1:Z);
A = [a(:),b(:),c(:)];
t = A(:,1).^2+A(:,2).^2==A(:,3).^2;
A = A(t,:);
Note: Using a well thought-out for-loop would probably be much faster and use less memory.