how to initialize a vector of structure

조회 수: 42 (최근 30일)
XAXRXTX
XAXRXTX 2014년 3월 4일
댓글: Jos (10584) 2014년 3월 4일
hello
so i have the example abouve
for i = 1 : n
structure.a = .......
structure.b = .......
.
.
structure.z = .......
my_vector(i) = structure;
end
the question is how i can preallocte the space size for the vector my_vector ?
thanks in advance
  댓글 수: 1
James Tursa
James Tursa 2014년 3월 4일
What is the stuff on the right-hand-side? Are you attempting to just get my_vector pre-allocated to hold the correct fields but not actually have anything in the field elements?

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

답변 (4개)

Mischa Kim
Mischa Kim 2014년 3월 4일
XAXRXTX, check out the documentation.
  댓글 수: 1
XAXRXTX
XAXRXTX 2014년 3월 4일
thanks Mischa Kim
but, but I do not want to initialize every field of the structure !!!

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


Kan-Hua
Kan-Hua 2014년 3월 4일
To preallocate memory, you need to put some values into the data structure that you are using. I think it's the design of Matlab. For example, to preallocate a memory for a 25x25 matrix, you need
mtx=zeros(25)
or
mtx=ones(25)
It is the same case for a structure array. To preallocate the memory space, you have to put some dummy values into every fields of the structure.

Jos (10584)
Jos (10584) 2014년 3월 4일
편집: Jos (10584) 2014년 3월 4일
As Mischa pointed out: preallocation of structures is easy:
S(1:5) = struct('a',zeros(10,1),'b','empty')
  댓글 수: 2
XAXRXTX
XAXRXTX 2014년 3월 4일
but , it's tedious to write S = struct('a','empty', 'b','empty', 'c','empty' ,'d','empty'...
................, 'z','empty');
there 's no other solution in fonction of the number of the structure field ???
Jos (10584)
Jos (10584) 2014년 3월 4일
If your fieldnames are known and you all want to set them to the same default value, in a 1-by-N array of structures S , try this
fn = {'a','b','c','d'} ; % this can be coded as well ...
value = zeros(1,10) ;
N=5 ;
S(1:N) = cell2struct(repmat({value},numel(fn),1),fn,1)

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


Kan-Hua
Kan-Hua 2014년 3월 4일
You can consider using table instead of structure array to store your data, which gives some flexibility to access the members. However, the version of you Matlab has to be 2013b or later.
Here's some example code of using table, which may solve your problem:
% initialise a table
zarray=zeros(1,3);
T=array2table(zarray,'VariableNames',{'colA','colB','colC'});
%show the initial values of the array
disp(T);
% assign the first row of the table by using names
T.colA(1)=1;
T.colB(1)=2;
T.colC(1)=3;
%Print out the table
disp(T);
% Alternatively, you can do it by index
for i=1:size(T,2)
T(2,i)={i*2};
end
% Print out the table
disp(T)

카테고리

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