Converting a cell array of dissimilar structs to an array of structs
Afficher commentaires plus anciens
In R2013b, say I have an cell array of structs like the following
% Some Mock Data
data{1} = struct('day', 'Monday', 'Temp', '35');
data{2} = struct('day', 'Tuesday', 'Temp', '34');
% Notice that data{3} has an extra field/value pair
data{3} = struct('day', 'Wednesday', 'Temp', '37', 'Comment', 'Rain');
I want to convert this into a struct array with 3 elements, but I want to "fill in" the missing field (Comment) in mystructarray(1) and mystructarray(2) with the empty array. Specifically, I want to end up with:
mystructarray(1)
ans =
day: 'Monday'
Temp: '35'
Comment: []
mystructarray(2)
ans =
day: 'Tuesday'
Temp: '34'
Comment: []
mystructarray(3)
ans =
day: 'Wednesday'
Temp: '37'
Comment: 'Rain'
I have tried the following, which is attractive for its readability, but it works ONLY if the 3 structures have the same field names.
mystructarray = [data{:}];
But because of the 'Comment' field in cell 3, I get the error:
Error using horzcat
Number of fields in structure arrays being concatenated do not match.
Concatenation of structure arrays requires that these arrays have the same set
of fields.
Is there an elegant way to build the desired structure array and "fill in" the missing fields to get what I want? I've tried CELLFUN but haven't gotten far with that function either.
Thank you. -Matt
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!