how preallocate structure for better memory

436 ビュー (過去 30 日間)
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 9 月 22 日
コメント済み: Dyuman Joshi 2024 年 3 月 27 日 8:47
I had created a structure made so:
head.number = 3;
head.pck_rcv = [1 0 0];
heads(2).number = 5;
head(2).pck_rcv = [1 1 0];
and so on.
How can I preallocate a structure?

採用された回答

Jan
Jan 2012 年 9 月 22 日
編集済み: Jan 2017 年 10 月 2 日
for k = n:-1:1 % Backwards!
head(k).number = 3;
head(k).pck_rcv = [1 0 0];
end
Now the final size of the struct array is created in the first iteration.
[EDITED] Alternatively:
head = struct('number', cell(1, 10), 'pck_rv', cell(1, 10));
Now head is a [1 x 10] struct array withe the fields 'number' and 'pck_rv'. Pre-allocating the contents of the fields is another job and you need a loop to do this. But now it can run in forward direction also.
  5 件のコメント
Igor Gitelman
Igor Gitelman 2022 年 5 月 20 日
thanks! that
head = struct('number', cell(1, 10), 'pck_rv', cell(1, 10));
work fine!
Dyuman Joshi
Dyuman Joshi 2024 年 3 月 27 日 8:47
I am accepting Jan's answer as it provides a robust solution to the question posted.

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

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 22 日
編集済み: Azzi Abdelmalek 2012 年 9 月 22 日
heads=struct('numbers',zeros(10,1), 'pck_rcv',zeros(10,3))
%then
for k=1:n
heads.numbers(k)=2
heads.pck_rcv(k,:)=[1 2 3]
end
  3 件のコメント
Jan
Jan 2017 年 10 月 2 日
@Alexandra: I do not agree. Salvatore asked for a struct array: "head(2).numbers and so on". Azzi's suggestion creates a scalar struct only.
Alexandra Simpson
Alexandra Simpson 2017 年 10 月 2 日
True, I just tried it out and realised it wasn't what I wanted either! Thanks for the response.

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


Walter Roberson
Walter Roberson 2012 年 12 月 13 日
head = struct('number', {3, 5}, 'pck_rcv', {[1 0 0], [1 0 1]})

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by