Time Complexity of 2D array

7 ビュー (過去 30 日間)
Yugal Gupta
Yugal Gupta 2019 年 11 月 12 日
コメント済み: Walter Roberson 2019 年 11 月 12 日
tic
vcp(i,:) = vcpa(:);
vcn(i,:) = vcna(:);
toc
where, vcpa and vcna are array of size 2. vcp and vcn are 2-D array. the i variable continuously increasing with time. As, the i is increasing, the time given by tic -toc is increasing. Therefore, as i becomes very large, the execution time bacomes very large. Can someone please illustrate the reason behinf this and suggest some alternate way to avoid such problem ?
Thanks in advance.

採用された回答

Cam Salzberger
Cam Salzberger 2019 年 11 月 12 日
編集済み: Cam Salzberger 2019 年 11 月 12 日
Hello Yugal,
What size are vcp and vcn before you start the loop? If you are doing something like this:
vcp = [];
vcn = [];
for i = 1:10
vcp(i, :) = vcpa(:);
vcn(i, :) = vcna(:);
end
then what is happenening is vcp and vcn are growing as the loop runs. They are initially allocated a very small amount of memory because they are empty arrays. As they grow in size, they need larger and larger contiguous memory blocks. This requires MATLAB to reallocate space for them, and copy over their existing data into the new memory block regularly throughout the loop.
If this is what is happening, I highly recommend preallocation of the arrays. You should be seeing a code analyzer warning about the array changing size every loop, which should warn you about this kind of thing in the future.
Also, it's not clear from your code snippet, but if you are not changing the value of vcpa and vcna within the loop, you can more easily create the arrays with something like:
vcp = repmat(vcpa(:), 1, nColumns);
vcn = repmat(vcna(:), 1, nColumns);
-Cam
  2 件のコメント
Yugal Gupta
Yugal Gupta 2019 年 11 月 12 日
That's working. Thank you very much.
Walter Roberson
Walter Roberson 2019 年 11 月 12 日
Also writing to columns is faster than writing to rows.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by