Strange behavior when initializing empty cell in struct()

조회 수: 3 (최근 30일)
Chandler
Chandler 2024년 6월 20일
댓글: Stephen23 2024년 6월 20일
Structs initialized with an empty cell using both {} and cell.empty within a struct() returns an empty struct object.
The following function reproduces that:
function print_hello_world()
obj = struct(MyProp=123, MyOtherProp={}); % or MyOtherProp=cell.empty
disp(obj)
disp(isempty(obj))
end
The obj variable is empty when running print_hello_world.
I have resorted to the following to go around this issue:
function print_hello_world()
obj = struct(MyProp=123);
obj.MyOtherProp = {};
disp(obj)
disp(isempty(obj))
end
The value of obj is as expected when running the above.
  댓글 수: 1
Stephen23
Stephen23 2024년 6월 20일
"Structs initialized with an empty cell using both {} and cell.empty within a struct() returns an empty struct object."

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

답변 (1개)

Aquatris
Aquatris 2024년 6월 20일
편집: Aquatris 2024년 6월 20일
If you want to define the property as empty, then you should use '[]' instead of '{}'.
obj = struct(MyProp=123, MyOtherProp=[]);
disp(obj)
MyProp: 123 MyOtherProp: []
This is an intended behaviour. Here is the relevant part of the documentation:
s = struct(field1,value1,...,fieldN,valueN) creates a structure array with multiple fields.
  • ...
  • If any value input is an empty cell array, {}, then output s is an empty (0-by-0) structure. To specify an empty field and keep the values of the other fields, use [] as a value input instead.
  댓글 수: 1
Stephen23
Stephen23 2024년 6월 20일
Or if an empty cell array is required:
obj = struct(MyProp=123, MyOtherProp={{}});

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

카테고리

Help CenterFile Exchange에서 Programming Utilities에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by