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

8 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Matt J
Matt J el 14 de Ag. de 2014
Editada: Matt J el 14 de Ag. de 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 comentarios
Layla
Layla el 14 de Ag. de 2014
Editada: Layla el 14 de Ag. de 2014
Awesome! ndgrid does the trick. Thank you!
Matt J
Matt J el 14 de Ag. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by