Which way is better?

4 ビュー (過去 30 日間)
madhan ravi
madhan ravi 2019 年 8 月 15 日
コメント済み: madhan ravi 2019 年 8 月 15 日
Note: This is not about preallocating variable in a loop. This is for general case.
For instance:
a(10,10) = 10; % the rest are filled with zeros
%or
a = zeros(10,10);
a(10,10) = 10;
  4 件のコメント
madhan ravi
madhan ravi 2019 年 8 月 15 日
Thank you sir Walter :)

サインインしてコメントする。

回答 (1 件)

Adam Danz
Adam Danz 2019 年 8 月 15 日
編集済み: Adam Danz 2019 年 8 月 15 日
In terms of speed, the 2nd option is 3.0 times faster on average (p<0.0001, Wilcoxon Signed Rank; 1 million individually timed iterations of the following 2 options).
a = []; % to reset a upon each loop
a(10,10) = 10;
% versus
a = []; % to reset a upon each loop
a = zeros(10,10);
a(10,10) = 10;
Declaring 'a' as zeros and then filling in the index (10,10) could also avoid other errors that option 1 may impose if 'a' is already a variable or function that exists.
Lastly, I think the 2nd option is more readable. Upon first glace of the first option, I'm wondering where 'a' came from.
  3 件のコメント
Rik
Rik 2019 年 8 月 15 日
There is nothing inherently wrong with the first option, but because it can cause confusion, you should add a comment there. It is also important to make sure that a doesn't exist before this executes.
madhan ravi
madhan ravi 2019 年 8 月 15 日
Thanks Rik.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by