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

2 vues (au cours des 30 derniers jours)
Layla
Layla le 14 Août 2014
Modifié(e) : Layla le 14 Août 2014
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

Réponse acceptée

Matt J
Matt J le 14 Août 2014
Modifié(e) : Matt J le 14 Août 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 commentaires
Layla
Layla le 14 Août 2014
Modifié(e) : Layla le 14 Août 2014
Awesome! ndgrid does the trick. Thank you!
Matt J
Matt J le 14 Août 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by