MATLAB Answers

Preallocating cells with unknown output size

28 ビュー (過去 30 日間)
Joel Schelander
Joel Schelander 2021 年 4 月 12 日 6:39
コメント済み: Bruno Luong 2021 年 4 月 12 日 9:50
I need to optimize my script. A thing I could do is preallocating, however the size of my output cell is unknown so my question is if it is worth it.
the output of the script is X, the size of X is not known.
Now I have:
X={};
*my script
X=nxn cell
If the output cell has the size 2x2 for example, can I do something like this:
not sure if it will increase the speed of my script
X=cell(999);
*my script
X=999x999 cell
*somehow reduce the size of X
X=2x2 cell
  5 件のコメント
Bruno Luong
Bruno Luong 2021 年 4 月 12 日 9:50
10 millions by 10 million cell?
I don't believe any existing HW can support that at the moment.

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

採用された回答

Bruno Luong
Bruno Luong 2021 年 4 月 12 日 7:42
編集済み: Bruno Luong 2021 年 4 月 12 日 8:25
If the size is not known, a good way is the to grow the preallocation array exponentially.
Rather than the assigment
X{i,j} = value;
Call
X = gassign(X,i,j,value);
where gassign implemented as follow
function X = gassign(X, i, j, val)
[m,n] = size(X);
if (i > m) || (j > n)
gidx = @(s,k) max(max(2*s,s+1),k);
X(gidx(m,i),gidx(n,j)) = {[]};
end
X{i,j} = val;
end
Then when finish truncate X to remove not filled cells.
You can start the script with X initialized as
X = {};

その他の回答 (1 件)

KSSV
KSSV 2021 年 4 月 12 日 6:46
You can try to initilize them as
X = cell([],[]) ;
You can check the timing using tic , toc.

タグ

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by