MATLAB: Help to improve runtime of 3 dimensional matrix

3d matix

hello everyone I wrote this code to read the indices of 3 dimensional matrix in a three column array. For n<100 (i.e. 100x100x100 matrix), MATLAB runs it in few hours. However, my final matrix is a 640x640x640 one for which MATLAB takes ages to finish. Could someone please help improve the code to run it faster. Any help is greatly appreciated.
clear all close all clc
n=640;
A = zeros(n,n,n);
Y = [0 0 0];
for i = 1:size(A(:, 1))
i
for j = 1:size(A(:, 2))
for k = 1:size(A(:, 3))
Y = [Y;i,j,k];
end
end
end

Best Answer

Your code is hugely inefficient because you expand the output array on each iteration. Read this to know more about why that is so inefficient, and how to avoid this penalty:
While you could solve this using array preallocation, loops, and indexing, a simpler and much more efficient solution is to use ndgrid (and avoid loops altogether):
>> [X,Y,Z] = ndgrid(1:n);
>> out = [Z(:),Y(:),X(:)];
Note that this will create a matrix out with 3*n^3 elements.