How can I improve this line of code perfomance wise?

7 vues (au cours des 30 derniers jours)
lit
lit le 8 Août 2023
Réponse apportée : Karan Singh le 1 Fév 2025 à 11:26
When using the profiler to look at the performance of a function I need to work with, I saw that one line takes up much time
invalidIndex = any((coords<ddims(1:3)) | (coords>ddims(4:6)),2);
So it just checks if the point contained are within the bounds. The size of coords is nx3
Is there any way this line can be improved perfomance wise. I couldn't think of anything else...
  2 commentaires
Walter Roberson
Walter Roberson le 8 Août 2023
You could try unvectorizing it and seeing how much difference that makes:
invalidIndex = coords(:,1)<ddims(1) | coords(:,2)<ddims(2) | coords(:,3)<ddims(3) | coords(:,1)>ddims(4) | coords(:,2)>ddims(5) | coords(:,3)>ddims(6);
My expectation is that this would be notably slower... but that you would have to measure the timing to be sure.
lit
lit le 8 Août 2023
actually, it does improve performance, so thank you very much!

Connectez-vous pour commenter.

Réponses (1)

Karan Singh
Karan Singh le 1 Fév 2025 à 11:26
Hi @lit,
In addition to what Walter stated, you can slo try to precompute bounds to avoid repested indexing.
In the original code, every time the condition (coords < ddims(1:3)) | (coords > ddims(4:6)) runs:
  1. ddims(1:3) and ddims(4:6) are accessed twice (one for < and one for >).
  2. MATLAB performs indexing operations multiple times, which can be slow for large datasets.
lowerBounds = ddims(1:3);
upperBounds = ddims(4:6);
invalidIndex = (coords(:,1) < lowerBounds(1)) | (coords(:,1) > upperBounds(1)) | ...
(coords(:,2) < lowerBounds(2)) | (coords(:,2) > upperBounds(2)) | ...
(coords(:,3) < lowerBounds(3)) | (coords(:,3) > upperBounds(3));

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by