Struct to double array conversion of empty function arguments no longer supported in 2015b or newer? Is this a new or old bug?

1 view (last 30 days)
I have a function that I use to load data into a array of structs. It can be called multiple times with each call appending to the existing array which is also passed in as an argument. A very cut down version looks like this:
function a = addto(a,b)
a(end+1) = struct('field1',b);
To initialize the array the first time I call it with an empty argument:
>> a = addto([],1)
a =
field1: 1
which works in all versions of matlab I've tried up to v2015b.
Once I hit v2015b though I get the following error:
>> a = addto([],1)
Conversion to double from struct is not possible.
Error in addto (line 3)
a(end+1) = struct('field1',b);
I can work around the issue by checking if the input is empty and not doing an array assignment if it is:
function a = addto_v2(a,b)
if isempty(a)
a = struct('field1',b);
else
a(end+1) = struct('field1',b);
end
I am curious though why the orginal code worked in previous versions and not recent versions.
Is this a bug in current versions?
I know that doing the following
>> a = []
>> a(1) = struct('field1',1)
outside of a function never worked so maybe this was a bug/side effect in older versions of Matlab but it was a handy one.
That said, I don't really understand why the conversion for an empty array is disallowed in the first place.
To me,
a = struct(...)
and
a(1) = struct(...)
should both work equally well when a is empty.

Answers (1)

Guillaume
Guillaume on 31 Aug 2016
Edited: Guillaume on 31 Aug 2016
To me, a = struct(...) and a(1) = struct(...) should both work equally well when a is empty.
When a is an empty structure array, Yes. When a is an empty double, I agree with matlab it should not, since you're changing the type of the variable.
Note that you'll have the same problem with other types that do not convert to double:
a = []; %create an empty double
a(end+1) = struct('x', 0) %not allowed since you're trying to put a structure into an array of double
a(end+1) = {'x'} %also not allowed to put a cell into an array of double
a(end+1) = datetime %also not allowed with classes. Cannot convert datetime to double
The workaround is to pass an empty structure (with the correct fields) instead of an empty double:
a = struct('x', {}); %create empty structure array
a(end+1) = struct('x', 1); %no error
So call your function with:
a = addto(struct('field1', {}), 1)
the first time round. Or indeed, test for empty double in the function.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!