Does A(m:n) trigger the explicit creation of an index array (m:n)?
Show older comments
I was under the impression that in an indexing expression A(m:n) when A is a numeric vector, Matlab was smart enough to optimize the operation by not explicitly constructing an intermediate index array I=(m:n), as it must in more general indexing expressions. I'm sure this was discussed in Answers or newsgroup posts from long ago (circa 2009).
However, the only way I can make sense of the different timings below is that there is substantial overhead coming from the expressions (1:end). So, am I mistaken? Do all indexing expressions A(expr) result in the explicit creation and storage of expr, even if it consists of a colon expression?
runTest()
function runTest
N=1e7;
[a]=deal( rand(N,1) );
timeit(@() f1(a))
timeit(@() f2(a))
timeit(@() f3(a))
function f1(a)
c=a(1:N)./2;
end
function f2(a)
a(1:N)=a(1:N)./2;
end
function f3(a)
a(:)=a(:)/2;
end
end
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!