Here is MATLAB's meshgrid
. I came up with these implementations in Mathematica:
{x, y} = With[{n = 10}, Table[#, {i, n}, {j, n}]] & /@ {j, i};
and
{x, y, z} = Array[List, {5, 5, 5}][[All, All, #]] & /@ {3, 2, 1}
but it seems that it's not fast enough. The following example is about three times slower than MATLAB.
(* Mathematica *)
(
{a, b} = With[{n = 3000}, Table[#, {i, n}, {j, n}]] & /@ {j, i};
c = a^2 + b^2 // N // Sqrt;
Compile[{}, Position[Unitize@FractionalPart@c, 0]][] // Length
) // AbsoluteTiming
%MATLAB
tic;
[a,b]=meshgrid(1:3000);
c=sqrt(a.^2+b.^2);
idx=find(c==round(c));
length(idx)
toc;
Can you recommend an efficient method?
Updated
(
{a, b} = {#, Transpose@#} &@ConstantArray[Range@3000, {3000}];
c = Sqrt@N[a*a + b*b];
SparseArray[Unitize@FractionalPart@c~BitXor~1]["NonzeroPositions"] // Length
) // AbsoluteTiming