2

I want to construct an struct object with three properties:

arg1 = 42;
arg2 = 'test';
arg3 = cell(0);

But if I try to initialize that object:

struct('arg1', arg1, 'arg2', arg2, 'arg3', arg3);

It returns an empty struct:

ans = 

  0×0 empty struct array with fields:

    arg1
    arg2
    arg3

I figured out the empty cell is the culprit, so if i initialize it without the empty cell it returns a correct value:

ans = 

  struct with fields:

    arg1: 42
    arg2: 'test'
    arg3: []

But I need my code to work with empty cells, and I don't know if or where they will be in one of the fields.

Is there a way to get out of this problem?

2 Answers 2

3

@Wolfie's explanation for the behavior is correct.

The workaround is to put the data in cell arrays like so:

>> struct('arg1', {arg1}, 'arg2', {arg2}, 'arg3', {arg3})

ans = 

  struct with fields:

    arg1: 42
    arg2: 'test'
    arg3: {}

This works because of this line in the documentation:

  • If any of the value inputs is a nonscalar cell array, then s has the same dimensions as the nonscalar cell array.

So we make all the value inputs cell arrays. {arg3} is the same as {{}}, a cell array with one element: an empty cell array.

Note that it is possible to create a struct array with this syntax:

>> struct('arg1', {1,2,3}, 'arg2', {arg2}, 'arg3', {arg3})

ans = 

  1×3 struct array with fields:

    arg1
    arg2
    arg3

Because the 'arg1' argument is a cell array with 3 elements, the created struct array also has 3 elements. The cell arrays with a single element are replicated across all cell arrays.

Sign up to request clarification or add additional context in comments.

Comments

2

This is documented behaviour:

s = struct(field,value) creates a structure array with the specified field and values. The value input argument can be any data type, such as a numeric, logical, character, or cell array.

  • If any of the value inputs is a nonscalar cell array, then s has the same dimensions as the nonscalar cell array. [...]

  • If value is an empty cell array {}, then 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

The take-away for you is the last line.

To get around this, you will have to do checks like

if iscell( argX ) && isempty( argX )
    argX = [];
end

If you always just have 3 items in your struct then this is fairly simple to implement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.