- Matlab must check for each element of i if it is a valid index (integer > 0). Then the maximum i must be determined for a pre-allocation (an iterative growing would be ways slower). Then the assignment can happen element by element.
- Matlab creates the variable var2 and re-uses the data of the right hand side. The time required for this does not depend on the size of the array.
- As in the case 1. but here Matlab is smart enough not to check each index, but only the first and the last one.
difference in declaring big arrays with iterators
조회 수: 1 (최근 30일)
이전 댓글 표시
Given an array (to use as an iterator)
i = [1:1e8];
What is the actual difference between declaring both arrays and why is the second option much faster?
var1(i) = 2*i;
var2 = 2*i;
I'm not even considering using a for loop to do it.
댓글 수: 0
답변 (1개)
Jan
2017년 3월 29일
편집: Jan
2017년 3월 29일
i = 1:1e8;
var1(i) = 2 * i;
var2 = 2 * i;
var3(1:1e8) = 2 * i;
While the right hand side is identical in all 3 cases, the assignment to the left hand side makes the difference. Let's see what happens:
Timings (R2016b, 64, Win7):
clearvars var*
tic; var1(i) = 2*i; toc
tic; var2 = 2*i; toc
tic; var3(1:1e8) = 2*i; toc
Elapsed time is 3.883811 seconds.
Elapsed time is 0.598112 seconds.
Elapsed time is 2.278915 seconds.
This is not the result I've expected. 2*i creates a temporary array needs a multiplication for each element. I assume that this takes nearly all of the time for version 2. Then assigniing the result in version 1. needs 5.5 times longer?!
Perhaps version 3 does not re-use the data of the temporary array. That this takes so much longer than creating 2*i is surprising.
By the way: Comparison with an older version 2009a:
Elapsed time is 3.987535 seconds.
Elapsed time is 0.894467 seconds.
Elapsed time is 2.437912 seconds.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!