Help to improve runtime of 3 dimensional matrix
Show older comments
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
KL
on 13 Mar 2018
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.
Pervez Ahmed
on 13 Mar 2018
Accepted Answer
More Answers (1)
Image Analyst
on 13 Mar 2018
Edited: Image Analyst
on 13 Mar 2018
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...
1 Comment
Pervez Ahmed
on 13 Mar 2018
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!