필터 지우기
필터 지우기

difference in declaring big arrays with iterators

조회 수: 1 (최근 30일)
Thales
Thales 2017년 3월 29일
편집: Jan 2017년 3월 29일
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.

답변 (1개)

Jan
Jan 2017년 3월 29일
편집: Jan 2017년 3월 29일
i = 1:1e8;
Note that the suqare brackets are not useful, see square brackets.
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:
  1. 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.
  2. 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.
  3. As in the case 1. but here Matlab is smart enough not to check each index, but only the first and the last one.
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by