I think this problem can be solved in a vecctorized manner as follows
%Generate all possible triplets.
[x1,x2,x3]=ndgrid(1:3,1:3,1:3);
v=[x1(:) x2(:) x3(:)];
Now define an anonymous function.
gcd3_test=@(a,b,c)(gcd(a,b)==1 & gcd(b,c)==1 & gcd(a,c)==1)
gcdTest=gcd3_test(v(:,1),v(:,2),v(:,3));
v=v(gcdTest,:);
Similarly generate the triplets for all your powers.
[x1,x2,x3]=ndgrid(3:10,3:10,3:10);
p=[x1(:) x2(:) x3(:)];
Then I guess you will have to use the for loop (but only one) as:
Important: I assume if you run the for
loop for powers 3:150
, and you need to store all x,y,z
then you will need lots of memory (35034 GB, even with single precision). You are not doing that in your code.
So do not try the following for loop.
%DO NOT RUN
for i=1:size(v,1)
vReplicated=repmat(v(i,:),size(p,1),1);
v_RaisedTo_P{i}=vReplicated.^p;
end
Note: Observe that you don't care about the order when conducting your GCD test (i.e. your if
condition. So I think you can filter out lot of triplets, but this will affect your power calculation.
allTriplets=sort(allTriplets,2);
allTriplets=unique(allTriplets,'rows'); %27 triplets reduce to 10