Possible bug in struct2table()
46 views (last 30 days)
Mohammad Abouali on 6 Apr 2016
When I try to convert a single structure to array using struct2table() I get an error.
But if I have an array of that structure it works just fine.
Try the following code:
% This ends up in error
myTBL = struct2table(singleStruct);
disp('I told you this ends up in error.');
% This wont end up in Error
structArray(1) = singleStruct;
structArray(2) = singleStruct;
myTBL = struct2table(structArray);
I have attached the singleStruct.mat for you guys to try.
Any work around?
Well, I usually have an array of those structure, this is really an special case that it is only one.
Matthew Eicholtz on 6 Apr 2016
Edited: Matthew Eicholtz on 6 Apr 2016
You may have already noticed this, but the error is due to having fields with an unequal number of rows. When you pass a scalar structure as input to struct2table(), it expects every row to be a different row in the table. This is problematic if the number of rows for each field varies.
In your provided data, it looks like there are three fields causing this problem: ELEVB, ELEVB_FR, and SNOEB.
One simple workaround is to encapsulate those fields into 1x1 cell arrays.
More Answers (1)
Lukas on 26 Apr 2017
As this error only occurs with (1x1) structs, there is a simple workaroud. To convert a struct into a table, use the following code:
largeStruct = repmat(struct,2,1);
table = struct2table(largeStruct);
table = table(1,:);