Filter löschen
Filter löschen

difference in declaring big arrays with iterators

1 Ansicht (letzte 30 Tage)
Thales
Thales am 29 Mär. 2017
Bearbeitet: Jan am 29 Mär. 2017
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.

Antworten (1)

Jan
Jan am 29 Mär. 2017
Bearbeitet: Jan am 29 Mär. 2017
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.

Community Treasure Hunt

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

Start Hunting!

Translated by