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

80 visualizzazioni (ultimi 30 giorni)
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(???)

Risposta accettata

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

Accedi per commentare.

Più risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by