Help to improve runtime of 3 dimensional matrix

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

2 Comments

This looks like a poorly formed example of your original problem. Instead of the dummy operation you do with Y, explain your operation. Without knowing that it's hard to help you.
Sorry, It is not a dummmy operation. This is my original problem. Once i locate the indices of all the voxels in the 3D matrix i then have to calculate the distance of every voxel from the centre of the matrix.

Sign in to comment.

 Accepted 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.

1 Comment

This worked. Thank you soo much stephen. I grately appreciate your help.

Sign in to comment.

More Answers (1)

Use meshgrid() to get a list of all coordinates, then use sqrt() to get distance to the middle. Untested code:
[X, Y, Z] = meshgrid(1:n, 1:n, 1:n);
distances = sqrt((X(:)-n/2).^2 + (Y(:)-n/2).^2 + (Z(:)-n/2).^2);
distances = reshape(distances, n, n, n);
and so on...

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!