How to create an empty struc with fields of a given struct?
이전 댓글 표시
I have a struct A with many fields:
A.a
A.b
...
A.z
Now I want to create a struct B, with the same fields:
B.a
B.b
...
B.z
With
B=struct(A)
B has also the same size as A, and all values of A are also included. But I want to have an empty struct with 0x1 dimension.
Background: in a loop I want to sort out some entries of A, that fit a certain criteria and write it into B. If I do
B=struct([])
B(n)=A(m)
then the structs do not match. Therefore I want to create B in advance and then assign it.
댓글 수: 1
Sara
2014년 3월 18일
A is not an array, so I don't see how you can do B(n)=A(m). Do you mean you want to do something like: 1) B.f = A.a, or 2) B.a(n) = A.b(m)?
채택된 답변
추가 답변 (3개)
The simplest and most efficient solution to the question posed is to just use indexing, e.g.:
>> A(1).x = 1;
>> A(1).y = 2;
>> A(2).x = 3;
>> A(2).y = 4
A =
1x2 struct array with fields:
x
y
>> B = A([])
B =
0x0 struct array with fields:
x
y
Using indexing we can also trivially obtain exactly the size requested in the original question:
>> B = A([],1)
B =
0x1 struct array with fields:
x
y
댓글 수: 3
Joe V
2020년 4월 17일
Brilliant! Recommending MathWorks include this in the MATLAB documentation.
Aryaman Mohapatra
2021년 3월 30일
^
Emily T. Griffiths
2021년 10월 14일
Love the simplicity of this. Thanks!
Ben Oeveren
2018년 8월 17일
편집: Ben Oeveren
2018년 8월 17일
I often use
fields = {'field1','field2','field2'}
c = cell(length(fields),1);
s = cell2struct(c,fields);
댓글 수: 2
Donghoon Yeo
2019년 5월 23일
편집: Donghoon Yeo
2019년 5월 23일
Easy and perfectly works for me
KAE
2019년 12월 20일
I think the line should be
fields = {'field1','field2','field3'}
So you get
s =
struct with fields:
field1: []
field2: []
field3: []
Binxu
2020년 4월 22일
Actually I just fond a super simple way similar to Stephen Cobeldick 's answer
It seems to me that repmat is a super useful tool for initializing many data structure.
summary =
struct with fields:
anova_F: 1.0172
anova_p: 0.4279
anova_F_bsl: 1.0156
anova_p_bsl: 0.4335
t: 8.7424
t_p: 5.9749e-18
t_CI: [2×1 double]
stats = repmat(summary,0,0);
>> repmat(summary,0,0)
ans =
0×0 empty struct array with fields:
anova_F
anova_p
anova_F_bsl
anova_p_bsl
t
t_p
t_CI
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!