Accessing Matlab arrays efficiently
2 views (last 30 days)
Show older comments
Murat Panayirci on 26 Nov 2020
Answered: Raunak Gupta on 5 Dec 2020
I have a question regarding the efficiency of accessing arrays in matlab. Below you can see a screenshot taken from profiler. I thought it was a little bit surprising that lines 22-23 takes a fraction of lines 26-27. I realize that I am accessing more element of the array, however I would not expect the difference to be this much.
I would be glad if you could advise me on any methods or tricks which could be helpful to improve the efficiency?
Raunak Gupta on 5 Dec 2020
As I can understand from Line 22-23, Mposition/Mvelocity are 2-D matrix and returned VpositionA/ VvelocityA are 1-D vectors. Since in Line 26-27 the same Mposition/Mvelocity is used in array indexing but here VindexB is an 1-D array rather than scalar value i, that is why the returned MpositionB/MvelocityB will be again a 2-D array rather than 1-D vector. I assume the size of VindexB is significantly greater than 1, that is why there is scaling of 10-15 times in time taken.
Here since the size of returned variable is different (1-D vs 2-D) in both set of lines, therefore we cannot compare the time taken. In my opinion if you are not thinking of using parfor then array indexing will work fine.
Find more on Matrix Indexing 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!