How to create a struct from a cell array of fieldnames and a cell array of values?

57 vues (au cours des 30 derniers jours)
How can you take a cell array array of fieldnames and a cell array of values, and convert them into a structure without looping?
names = {'f1', 'f2'};
values = {1 2};
structure = struct(???)

Réponse acceptée

Matt J
Matt J le 18 Jan 2013
Modifié(e) : Matt J le 18 Jan 2013
args=[names;values];
structure = struct(args{:})
  1 commentaire
Eric Sampson
Eric Sampson le 18 Jan 2013
Brilliant! I couldn't figure out how to make the fieldnames and values alternate, but your solution is the key :) Thanks Matt!

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 18 Jan 2013
cell2struct(values,names,2)
  2 commentaires
Eric Sampson
Eric Sampson le 18 Jan 2013
I always find the cell2struct syntax tricky. I figured that it should be possible, but gave up. Thanks!
Jan
Jan le 18 Jan 2013
It is not documented but even slightly faster, to omit the 3rd input dimension, when values and names are {nx1} cells.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by