# How do I pre-allocate memory for a structure?

119 Ansichten (letzte 30 Tage)
WANYI ZHANG am 27 Mär. 2019
Beantwortet: Michael am 15 Jun. 2022
Can anyone help me to fix pre-allocation memory for a structure output?
I have a structure function which have 18 elements, it has two imputs and give results 16 outputs and two inputs.
If I want to pre-allocate the output memory how can I do it.
Here is the code:
phase_in = ?????; % what should be in question marks ( I did zeros(length(v_in),refprop))
for i=1:length(v_in)
phase_in(i) = refprop(v_in(i),T_in,r410a);
end
r410 is my structure function, and v_in and T_in are inputs, I will calculate 100 times to calculate phase_in.
If I skip pre-allocation, the output will give me 1*1000 structure. In this case, I tried to pre-allocate phase_in=zeros(100,18),
but it gave me error'' Conversion to double from struct is not possible.''
##### 1 KommentarKeine anzeigenKeine ausblenden
Stephen23 am 27 Mär. 2019
Bearbeitet: Stephen23 am 27 Mär. 2019
By far the fastest and simplest an solution is to allocate the last element first, for example by simply looping over the indices backwards (as Walter Roberson explained in their answer). This topic has been discussed on the MATLAB blogs:
Do NOT use a cell array of structures, this just makes your data storage more complex and less efficient, and means that you cannot use a simple comma-separated list for accessing the structure data:

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

KSSV am 27 Mär. 2019
S = struct ;
for i = 1:10
S(i).Rand = rand ;
S(i).loop = i ;
end
##### 8 Kommentare7 ältere Kommentare anzeigen7 ältere Kommentare ausblenden
WANYI ZHANG am 27 Mär. 2019
Thanks a lot.
It is all worked.
I appreciate you.
Thanks again.

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (2)

Walter Roberson am 27 Mär. 2019
Loop backwards from length down to 1 so that the highest offset is assigned to first so it will not need to grow the array afterwards.
##### 2 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Walter Roberson am 27 Mär. 2019
(Or if it does exist, that it is a compatible structure and no larger than what will be needed.)

Melden Sie sich an, um zu kommentieren.

Michael am 15 Jun. 2022
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2017b

### Community Treasure Hunt

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

Start Hunting!