Create a struct from two cell arrays
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Deepa Maheshvare
am 22 Aug. 2021
Bearbeitet: Awais Saeed
am 22 Aug. 2021
I've the following cell arrays
keys =
4×1 cell array
{'n' }
{'key12'}
{'key13'}
{'key14'}
values =
4×1 cell array
{[ 10]}
{[ 1]}
{[ 1]}
{'Hello'}
When I try to create a struct in the following manner
args=[names;values];
structure = struct(args{:})
the below error occurs
Error using struct
Field names must be non-empty character vectors or a string scalars.
Error in setting.load_setting (line 19)
structure = struct(args{:})
Could someone please have a look?
0 Kommentare
Akzeptierte Antwort
Awais Saeed
am 22 Aug. 2021
keys = {'n', 'key12', 'key13','key14'};
values = {10, 1 1 , 'Hello'};
names = {'f1', 'f2', 'f3', 'f4'};
args=[names;values];
structure = struct(args{:})
Seems to work for me
1 Kommentar
Awais Saeed
am 22 Aug. 2021
Bearbeitet: Awais Saeed
am 22 Aug. 2021
Perhaps you are trying with
names = {'f1', 'f2', '', ''};
This will cause problems. If you must proceed this way I think it would be better to replace those empty cells with some string
keys = {'n', 'key12', 'key13','key14'};
values = {10, 1 1 , 'Hello'};
names = {'f1', 'f2', '', ''};
% get locations of empty cell elements
idx = cellfun('isempty',names);
[row, col] = find(idx);
% replace those empty cells with some string
for jj = 1:1:size(col,2)
idx = col(jj);
names{idx} = ['skip' num2str(jj)];
end
% Now concatenate cells
args=[names;values]
% convert to struct
P = struct(args{:});
struct2table(P)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!