How do I pre-allocate memory for a structure?
94 次查看(过去 30 天)
显示 更早的评论
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.''
Thanks a lot in advance.
1 个评论
Stephen23
2019-3-27
编辑:Stephen23
2019-3-27
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:
and also in many other Answers threads (with examples) e.g.:
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:
采纳的回答
KSSV
2019-3-27
S = struct ;
for i = 1:10
S(i).Rand = rand ;
S(i).loop = i ;
end
8 个评论
KSSV
2019-3-27
dm=zeros(length(v_in),1);
phase_in = cell(length(v_in),1);
fluid_up = struct ;
for i=1:length(v_in)
phase_in{i} = refprop(v_in(i),T_in,r410a);
fluid_up(i).P1 = phase_in{i,1}.P;
fluid_up(i).rho = 1/phase_in{i,1}.vg;
dm(i) = orifice(fluid_up(i),P_d,orifice_params);
end
更多回答(2 个)
Walter Roberson
2019-3-27
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 个评论
Walter Roberson
2019-3-27
(Or if it does exist, that it is a compatible structure and no larger than what will be needed.)
Michael
2022-6-15
编辑:Steven Lord
2023-7-7
repmat offers another solution for preallocating structures:
[SL: Removed broken link to code generation documentation, added link to the main repmat function documentation page.]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!