- 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!