Initializing Array of Structures/Objects

조회 수: 80 (최근 30일)
Sven
Sven 2015년 9월 5일
댓글: mary 2022년 11월 17일
I simply want to set each struct in a struct-array. I set structarray to [] as it is an object property in my case, where it is being initialized as emtpy array. My first approach looks like:
structarray = [];
for i=1:10
structarray(i) = struct('index', i);
end
I get the following error: 'The following error occurred converting from struct to double: Error using double Conversion to double from struct is not possible.'
I can use an if else check and set the first element by:
structarray = struct('index', i);
Is there any easy way to write this straightforward similar to my code above?

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 9월 5일
Sven - why not use arrayfun to apply a function to each element in the array. In this case, your function would create a struct with a single field called index where its value is assigned its position/index within the array. The following should do what you require
myStructArray = arrayfun(@(x)struct('index',x),1:10)
Note how the first input to arrayfun is the function that creates the struct given an input parameter. The value of each parameter is determined from the second input to arrayfun - an array of indices from one to ten.
Try the above and see what happens!
  댓글 수: 3
Bruno Luong
Bruno Luong 2022년 11월 17일
myStructArray = arrayfun(@(i1,i2)struct('index1',i1,'index2',i2),zeros(1,10),zeros(1,10))
myStructArray = 1×10 struct array with fields:
index1 index2
mary
mary 2022년 11월 17일
I found the answer:
myStructArray = arrayfun( @(x)struct('index1',x,'index2',x),zeros(1,10) )

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2015년 9월 6일
structarray = struct('index', repmat({[]}, 1, 10));

카테고리

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