Possible bug in struct2table()

33 vues (au cours des 30 derniers jours)
Mohammad Abouali
Mohammad Abouali le 6 Avr 2016
Commenté : Peter Perkins le 1 Oct 2018
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:
load singleStruct.mat
% This ends up in error
try
myTBL = struct2table(singleStruct);
catch
disp('I told you this ends up in error.');
end
% 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.
  1 commentaire
Steven Lord
Steven Lord le 6 Avr 2016
What is the FULL text of the error message?

Connectez-vous pour commenter.

Réponse acceptée

Matthew Eicholtz
Matthew Eicholtz le 6 Avr 2016
Modifié(e) : Matthew Eicholtz le 6 Avr 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.
  4 commentaires
Austin Healy
Austin Healy le 20 Sep 2018
Thanks for the explanation and now that I see AsArray I'll remember to set it. I understand your point but frankly, I think the default value for AsArray should be true. In a programmatic setting I can't think of a situation where I would so radically want to change behavior when I happen to have a scalar array
Peter Perkins
Peter Perkins le 1 Oct 2018
That's why the parameter exists. Interactively, it would be a pain to type all that. Programmatically, it's a good idea for the reason you cite. It's similar to "always use the DIM argument to the mean function when you are writing a script or function that will be reused."

Connectez-vous pour commenter.

Plus de réponses (1)

Lukas
Lukas le 26 Avr 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,:);

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by