フィルターのクリア

what is the difference between using the zeros array or nan array ?!

35 ビュー (過去 30 日間)
Ano
Ano 2017 年 5 月 20 日
コメント済み: John D'Errico 2017 年 5 月 20 日
Hello! I would like to know what is the difference between initializing an array using the zeros array and nan array in matlab? is there any advantages of using one of them A or B? Thank you!
A= zeros (100,100);
B = nan (100,100);

採用された回答

John D'Errico
John D'Errico 2017 年 5 月 20 日
編集済み: John D'Errico 2017 年 5 月 20 日
No difference in theory. I frequently use NaNs because that way, if I am doing something, and then want to verify I have filled the entire array, NaNs would be easier to spot.
zeros seems to be faster, and consistently so. This is certainly due to the way they are implemented internally.
timeit(@() zeros(1000))
ans =
0.0030123
timeit(@() nan(1000))
ans =
0.0044756
So, is the time nearly inconsequential? Yes.
Is the difference significant? Yes. NaN takes roughly 50% more time than zeros.
Do I care, unless I have a vast number of calls to either of these operations? NO. And since I try NEVER to write code that has a vast number of calls to any such operator, there is little to worry about for me.
  2 件のコメント
Steven Lord
Steven Lord 2017 年 5 月 20 日
From a non-technical standpoint, if zero is a meaningful value for the quantity you want to store in the array, preallocating with zeros means you can't distinguish between an element that has been filled with 0 and an element that hasn't been filled. For example, consider an array that will store temperatures. In that case, you may want to preallocate using NaN or Inf instead.
John D'Errico
John D'Errico 2017 年 5 月 20 日
What I was trying to say, but Steve said it better. NaN (or inf) is a good way to flag if you did something wrong, especially if zero is possible.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by