How to speed up for-loop for creating cell with coordinate numbers as contents

1 view (last 30 days)
I have the following script that constructs a 3D cell where the contents of each cell element are its XYZ coordinates. There has to be a faster way to do this, but I can't think of it. Anyone have advice? Here's the current (very slow!) for-loop:
MatchDimensions = [512 512 414];
X = MatchDimensions(1);
Y = MatchDimensions(2);
Z = MatchDimensions(3);
MatchCoordinates = cell(X, Y, Z);
for z = 1:Z
for y = 1:Y
for x = 1:X
MatchCoordinates{x, y, z} = [x y z];
end
end
end

Accepted Answer

Matt J
Matt J on 14 Aug 2014
Edited: Matt J on 14 Aug 2014
Cells are not a great way to store large data and should be unnecessary when the data are all the same size. But, you could try this:
[X,Y,Z]=ndgrid(1:512,1:512,1:414);
MatchCoordinates=reshape(num2cell([X(:),Y(:),Z(:)],2),[512,512,414]);
  2 Comments
Matt J
Matt J on 14 Aug 2014
It would be better to organize your data like this,
>> MatchCoordinates=reshape([X(:),Y(:),Z(:)].',3,512,512,414);
>> MatchCoordinates(:,2,4,5)
ans =
2
4
5

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!