필터 지우기
필터 지우기

Initializing a struct with n-d fields.

조회 수: 95 (최근 30일)
Leo Simon
Leo Simon 2013년 11월 18일
답변: Julian 2013년 11월 19일
Hi, I have a struct with an indeterminate number of fields. For (very good) reasons I don't want to go into, I want to initialize each of these fields with NaNs. The closest I can find is a post by Shane, in 200 http://blogs.mathworks.com/loren/2008/02/01/structure-initialization/#15%20Initializing%20a%20struct%3Estructure-initialization/#15
that suggests something along the lines of
data = repmat(struct('field1',NaN(2,2,2),'fieldN',NaN(5)),[1,2,3,4]);
What I would like to do instead is build the structure in a loop, something along the lines of:
data = struct();
for ii=1:7;
data = repmat(struct(field{ii},NaN(2,2,2)),[1,2,3,4]);
end
But of course this doesn't work because the loop line wipes out the pre-existing struct.
There is presumably a way of initializing additional fields in a similar way, without having to do everything in the one line as Shane suggests. Obviously I could build a long string in a loop and evaluate it, but that's a pain.
Any advice would be most appreciated.

채택된 답변

Matt J
Matt J 2013년 11월 19일
for ii=1:7;
data.(field{ii}) = NaN(2,2,2);
end
data=repmat(data,[1,2,3,4]);
  댓글 수: 1
Leo Simon
Leo Simon 2013년 11월 19일
Thanks, Matt J, this is exactly what I needed.

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

추가 답변 (2개)

Julian
Julian 2013년 11월 19일
An alternative approach just using builtin functions
C = cell(numel(field),1,2,3,4); % pre-allocate cell-array to required size
C(:) = {NaN(2,2,2)}; % populate cell-array
C = cell2struct(C,field); % convert to struct array, field names along dimension 1

David Sanchez
David Sanchez 2013년 11월 19일
Initialization as NaN of three fields called field1, field2, field3:
for k=1:3;
data.(strcat('field',num2str(k))) = NaN;
end
>> data
data =
field1: NaN
field2: NaN
field3: NaN

카테고리

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