필터 지우기
필터 지우기

pre-allocating structures

조회 수: 6 (최근 30일)
Romain W
Romain W 2012년 3월 1일
Hello everyone,
I'm trying to pre-allocate memory for a structure defined as follows:
% S : Structure containing geometrical description of polygons.
% S(i) contains all information relative to the i-th shape
% S(i).P(j) gives access to the geometrical description of the j-th
% element of the i-th shape.
% XData : S(i).P(j).x : Vector
% YData : S(i).P(j).y : Vector
% Hole : S(i).P(j).hole : Binary value
I'd like to pre-allocate before the following loop:
for i=1:ne
for j=1:2
S(i).P(j).x = v_proj(f(i,j),1);
S(i).P(j).y = v_proj(f(i,j),2);
S(i).P(j).hole = 0;
end
end
I'd like to have a number of shapes ne.
But I don't really know how to do that. Any help would be more than welcome.
Thank you very much,
% Romain

채택된 답변

Oleg Komarov
Oleg Komarov 2012년 3월 1일
One way to preallocate:
P(1:2) = struct('x',zeros(10,1),'y',zeros(1,2),'hole',false);
ne = 10;
[S(1:ne).P] = deal(P);
  댓글 수: 1
Romain W
Romain W 2012년 3월 1일
thank you very much, it works just fine.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2012년 3월 1일
You can create the last element at first to do an implicite pre-allocation:
for i=ne:-1:1
for j=[2,1]
S(i).P(j).x = v_proj(f(i,j),1);
S(i).P(j).y = v_proj(f(i,j),2);
S(i).P(j).hole = 0;
end
end
  댓글 수: 2
Oleg Komarov
Oleg Komarov 2012년 3월 1일
It doesn't work since structures use pointers:
S(20).P(20).x = 1:20;
S : 816.00 B
S(19).P(19).x = 1:20;
S : 1.37 KB
Jan
Jan 2012년 12월 13일
편집: Jan 2012년 12월 13일
@Oleg: What does not work and why are the sizes of S interesting here? The code I've posted pre-allocates S in one step and the fields P for each S(:) in one step also. There is no way to pre-allocate all ne elements of P simulataneously, because they are distinct arrays. As far as I can see [S(1:ne).P] = deal(P) creates shared data copies for the contents of all S(:).P, such that writing values later on will consume additional time by creating deep data copies at first. Therefore your pre-allocation is faster only if no data are written and this is rarely needed in real world programs.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by