# Create and populate field on existing structure. Impossible?

조회 수: 2 (최근 30일)
편집: Stephen23 2023년 6월 17일
Hi all,
I have created a structure and populated it with data from a cell array:
MyStruct=struct('Field1',num2cell(DFullData{1,1}),'Field2',num2cell(DFullData{1,2}))
Fabulous:
MyStruct =
1x461 struct array with fields:
Field1
Field2
Note that
>> MyStruct(1)
ans =
Field1: 7.354373336826041e+05
Field2: 2.407360200100000e+10
>> MyStruct(2)
ans =
Field1: 7.354373336883913e+05
Field2: 2.319540190100000e+10
How on earth do I create a Field3 and populate it like above (obviously without using a loop)?
Everything I tried ("setfield" and every permutation of squared and curly brackets!) populates only the first element with the whole cell array.
>> MyStruct().Field3=num2cell(DFullData{1,5})
>> MyStruct(1)
ans =
Field1: 7.354373336826041e+05
Field2: 2.407360200100000e+10
Field3: {1x461 cell}
>> MyStruct(2)
ans =
Field1: 7.354373336883913e+05
Field2: 2.319540190100000e+10
Field3: []
What is the correct syntax to populate each element of Field3 with each element of the cell array? Thanks!

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

### 채택된 답변

Arthur 2013년 9월 13일
Did you try this?
[MyStruct.Field3] = DFullData{:,5};
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Stephen23 2023년 6월 17일
편집: Stephen23 2023년 6월 17일

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

### 추가 답변 (2개)

Azzi Abdelmalek 2013년 9월 13일
n=numel(DFullData{1,5})
for k=1:n
MyStruct(k).Field3=DFullData{1,5}(k)
end
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

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

Azzi Abdelmalek 2013년 9월 13일
f=fieldnames(MyStruct)
g=struct2cell(MyStruct)
[n,m]=size(g)
g(n+1,1:m)=num2cell(DFullData{:,5})
MyStruct=cell2struct(g,[f;{'field3'}])
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Thank you very much, this is a bit convoluted but does the job! I am surprised that we have to go to such lenghts to perform such a simple operation, you'd think Mathworks would have thought about it. Oh well... Thanks again :)

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

### 카테고리

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