Inefficient or slow use of colon-operator within a matrix
4 Comments
"It appeared that the use of colon-operator ... is incredibly slow or inefficient"
Unfortunately those timings are meaningless as they compare apples with oranges.
"Why is the use of ":" / Colons 70 times (!!) slower"
Slower than what: not doing that operation? Not doing an operation takes zero seconds, so the factor is infinity.
Note that you are comparing two totally different sequences of operations:
- allocation of a variable to a new variable, which uses no new memory (just adds a pointer to the same array).
- subscript indexing into a variable creating a new array in memory to be allocated for the extracted elements (all 125 million of them), and then allocation of that array to a new variable.
So really all you are measuring is the time required to create a 125 million element array.
@Stephen, since the last statement given in OP's code, Data3 = Data(:,:,:,1);. Is also assigning the complete matrix Data to Data3, it is reasonable to expect that MATLAB execution engine will see this advance and optimize the execution.
"Indexing takes time, because operations take time."
then how can you explain the following execution times, here I am also indexing Data.
Data = ones(500,500,500); clear Data2 Data3; tic Data2 = Data; toc; %--> Elapsed time is 0.000034 seconds. tic Data3 = reshape(Data(:), size(Data)); toc; %--> Elapsed time is 0.000073 seconds.
@Ameer,
In term of memory Data(:) is just a reshape, that means that the only thing that needs copying into new memory is the matrix header (that specifies the size of the matrix). The matrix content itself does not need copying. The explicit reshape is the same, only the header needs copying. So, Data2, Data, the temporary Data(:) and Data3 all point to the same chunk of memory. Hence why it takes no time.
You're going to incur the copying penalty, as soon as you change just one value of any of these shared copy.
Note: you can use James Tursa's isshared to verify this.
Thanks @Guillaume, the copy-on-write makes complete sense to explain the execution time. Although, when will MATLAB use copy-on-write is still not clear. As you mentioned in your comment Data(:) is just a reshape, similarly colon operator documentation page also describes Data(:,:) as reshape operation but the execution of following lines show that this does not result in creating a reference to Data rather a copy is created immediately
tic Data3 = Data(:, :); toc % Elapsed time is 0.600342 seconds.
Accepted Answer
More Answers (0)
Categories
Find more on Matrices and Arrays 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!