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

68 Ansichten (letzte 30 Tage)
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(???)

Akzeptierte Antwort

Matt J
Matt J am 18 Jan. 2013
Bearbeitet: Matt J am 18 Jan. 2013
args=[names;values];
structure = struct(args{:})
  1 Kommentar
Eric Sampson
Eric Sampson am 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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by