Basic question about initializing variables
3 次查看(过去 30 天)
显示 更早的评论
What's the difference between
a = [ 1 2 3 ];
and
a = zeros(1,3);
a = [ 1 2 3 ];
Performance? Logic? I'm just interested to know. Thanks for your help!
0 个评论
采纳的回答
Jan
2017-4-20
In
a = zeros(1,3);
a = [ 1 2 3 ];
Matlab reserves memory for 3 doubles and fills then with zeros in the first line. In the second line this memory is freed and a new vector is created. This needs about the double work compared to creating [1, 2, 3] directly and in consequence is a waste of time only.
This is not a pre-allocation. A pre-allocation would mean, that the reserved memory is re-used later:
a = zeros(1, 3);
a(1) = 1;
a(2) = 2;
a(3) = 3;
or
a = zeros(1, 3);
a(:) = 1:3;
The "(:)" is essential here, because it tells Matlab to overwrite the contents of the formerly existing memory.
6 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!